How to check hasClass in html tables - javascript

When I create tables and I would like to check whether each element hasClass by clicking correcponding cells(above cells)
My work is like below.
But it didn't work well.
How can I achieve it ?
And What is wrong point?
Thanks
$("td.number").click(function(){
id=$(this).index();
$("td.color").index(id).hasClass("aqua");
});
td {
transition-duration: 0.5s;
border: solid black 1px;
padding: 5px;
}
.number{
cursor:pointer;}
table {
border-collapse: collapse;
}
.color{
padding:5px;
}
.aqua {
background-color: aqua;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id=calendar></div>
<script>
let html = ''
html += '<table>';
let i = 0;
html += '<tr>';
for (let d = 0; d < 15; d++) {
i = i + 1;
html += '<td class="number">' + i +'</td>'
}
html += '</tr>';
for (let w = 0; w < 1; w++) {
html += '<tr>';
for (let d = 0; d < 15; d++) {
html += '<td class="color"></td>'
}
html += '</tr>';
}
html += '</table>'
document.querySelector('#calendar').innerHTML = html;
const arr = [1, 2, 10, 11, 14];
$("td.color")
.filter(function() { return arr.includes($(this).index()+1); })
.addClass('aqua');
</script>

.index() is used to return the position as an integer, not to find an element based on its index - for that you want .eq()
Updated fiddle:
$("td.number").click(function(){
id=$(this).index();
$(this).toggleClass("aqua", $("td.color").eq(id).hasClass("aqua"));
});
td {
transition-duration: 0.5s;
border: solid black 1px;
padding: 5px;
}
.number{
cursor:pointer;}
table {
border-collapse: collapse;
}
.color{
padding:5px;
}
.aqua {
background-color: aqua;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id=calendar></div>
<script>
let html = ''
html += '<table>';
let i = 0;
html += '<tr>';
for (let d = 0; d < 15; d++) {
i = i + 1;
html += '<td class="number">' + i +'</td>'
}
html += '</tr>';
for (let w = 0; w < 1; w++) {
html += '<tr>';
for (let d = 0; d < 15; d++) {
html += '<td class="color"></td>'
}
html += '</tr>';
}
html += '</table>'
document.querySelector('#calendar').innerHTML = html;
const arr = [1, 2, 10, 11, 14];
$("td.color")
.filter(function() { return arr.includes($(this).index()+1); })
.addClass('aqua');
</script>

You need to change your selector by making use of eq() and not index() to access the element you need:
$("td.number").click(function(){
var id = $ (this).index();
$("td.color").eq(id).hasClass("aqua");
});

Related

How do i exclude labels from a sitemap generator in javascript for Blogger

So I have this script that shows a sitemap of my blog just like this:
And when its clicked shows like this:
Basically I want to exclude some tags from showing in the site, and Display the posts of the first label when loaded like the second image.
I tried using cat_remove = ['Label12', 'Label13']; to remove labels but didn't work.
And tried using show_post (cat [0] .term, 1,0); to display post of the first label when loaded but that didn't work either.
I hope I've documented everything. Thanks in advance.
var cat_home = 'https://myblog.blogspot.com';
cat_numb = 4;
cat_pre = '< Anterior';
cat_nex = 'Siguiente >';
var cat_name;
var cat_start;
var cat_class;
function show_post2(a) {
var tt = a.feed.openSearch$totalResults.$t;
dw = '';
dw += '<ul>';
for (var i = 0; i < cat_numb && i < a.feed.entry.length; i++) {
var entry = a.feed.entry[i];
cat_title = entry.title.$t;
for (var j = 0; j < entry.link.length; j++) {
if (entry.link[j].rel == 'alternate') {
var cat_url = entry.link[j].href
}
}
dw += '<li>';
dw += (cat_start + i) + '. ' + cat_title + '';
dw += '</li>'
}
dw += '</ul>';
dw += '<div id="navi-cat">';
if (cat_start > 1) {
dw += '' + cat_pre + ''
}
if ((cat_start + cat_numb - 1) < tt) {
dw += '' + cat_nex + ''
}
dw += '<span>' + cat_start;
if (cat_start != tt) {
dw += ' – ' + (cat_start + i - 1)
}
dw += ' / ' + tt + '</span>';
dw += '</div>';
document.getElementById('show-post').innerHTML = dw + '<style type="text/css">.cat-' + cat_class + ' a{background:#bbb!important;color:#fff!important}<\/style>'
}
function show_post(a, b, c) {
var d = document.getElementsByTagName('head')[0];
e = document.createElement('script');
e.type = 'text/javascript';
e.setAttribute('src', cat_home + '/feeds/posts/default/-/' + a + '?alt=json-in-script&start-index=' + b + '&max-results=' + cat_numb + '&callback=show_post2');
d.appendChild(e);
cat_name = a;
cat_start = parseInt(b), cat_class = c
}
function show_cat(a) {
var cat = a.feed.category;
dw = '';
dw += '<ul>';
for (var i = 0; i < cat.length - 1; i++) {
for (var j = i + 1; j < cat.length; j++) {
if (cat[i].term > cat[j].term) {
cat_hv = cat[i].term;
cat[i].term = cat[j].term;
cat[j].term = cat_hv
}
}
}
for (var i = 0; i < cat.length; i++) {
dw += '<li class="cat-' + i + '">';
dw += '<a href="" onclick="show_post(\'' + cat[i].term + '\',\'1\',\'' + i + '\');return false" title="';
dw += cat[i].term;
dw += '">';
dw += cat[i].term;
dw += '</a>';
dw += '</li>'
}
dw += '</ul>';
document.getElementById('show-cat').innerHTML = dw
}
document.write('<script type="text/javascript" src="' + cat_home + '/feeds/posts/default?alt=json-in-script&max-results=0&callback=show_cat"><\/script>');
#show-cat {
float: left;
margin-right: 33px;
width: 165px;
height: 310px;
overflow-x: hidden;
overflow-y: auto;
line-height: 18px
}
#show-cat ul {
margin: 0;
border-top: 0 solid rgba(0, 0, 0, 0.1);
padding: 0
}
#show-post ul li {
list-style-type: none;
margin: 0 0 0 -25px;
padding: 10px 0;
border-bottom: 1px solid rgba(0, 0, 0, 0.1)
}
#show-post ul li:hover {
margin-right: 10px;
border-color: #fcd3d3
}
#show-cat ul li a {
display: block;
padding: 10px;
border-bottom: 1px solid rgba(0, 0, 0, 0.1);
transition: initial
}
#navi-cat a:hover {
color: #fff!important
}
#show-cat ul li:last-child a {
border-bottom: none
}
#show-cat ul li a,
#navi-cat a {
background: #fff;
color: #555;
font-weight: bold;
text-decoration: none
}
#show-cat ul li a,
#navi-cat a,
#navi-cat span {
font-size: 13px
}
#show-cat ul li a:hover,
#navi-cat a:hover {
background: #666;
color: #fff
}
#show-post {
float: left;
width: 69%;
line-height: 1.6em
}
#show-post a {
color: #333;
font-size: 14px
}
#show-post a:hover {
color: #f14b4b
}
#navi-cat {
padding: 20px 0
}
#navi-cat a {
padding: 5px 10px;
background: rgba(0, 0, 0, 0.7);
margin: 0 5px 0 0;
color: #fff;
border-radius: 3px;
}
#navi-cat a:nth-child(2) {
background: #f14b4b;
margin: 0 10px 0 0;
color: #fff
}
#navi-cat span {
float: right;
padding: 5px 0;
font-size: 12px;
color: rgba(0, 0, 0, 0.5);
font-weight: 700
}
#show-cat::-webkit-scrollbar {
width: 8px;
height: 8px
}
#show-cat::-webkit-scrollbar-track {
background-color: rgba(0, 0, 0, .1);
}
#show-cat::-webkit-scrollbar-thumb:hover {
background-color: rgba(0, 0, 0, .6)
}
#show-cat::-webkit-scrollbar-thumb {
background-color: rgba(0, 0, 0, .4);
transition: all 400ms ease-in-out
}
#media screen and (max-width:768px) {
#show-cat {
width: 35%
}
#show-post {
width: 59%
}
}
#media screen and (max-width:480px) {
#show-cat {
width: 100%;
margin: 20px 0
}
#show-post {
width: 100%
}
}
<div id='show-cat'></div>
<div id='show-post'>
<div style='clear:both'></div>
Here is how to exclude labels
cat = cat.filter(i => !["Label12","Label13"].includes(i.term));
Place it after this variable var cat = a.feed.category;
To display posts of the first label when loading, use this show_post(cat[0].term, 1) after sorting.
var cat_home = 'https://myblog.blogspot.com';
cat_numb = 4;
cat_pre = '< Anterior';
cat_nex = 'Siguiente >';
var cat_name;
var cat_start;
var cat_class;
function show_post2(a) {
var tt = a.feed.openSearch$totalResults.$t;
dw = '';
dw += '<ul>';
for (var i = 0; i < cat_numb && i < a.feed.entry.length; i++) {
var entry = a.feed.entry[i];
cat_title = entry.title.$t;
for (var j = 0; j < entry.link.length; j++) {
if (entry.link[j].rel == 'alternate') {
var cat_url = entry.link[j].href
}
}
dw += '<li>';
dw += (cat_start + i) + '. ' + cat_title + '';
dw += '</li>'
}
dw += '</ul>';
dw += '<div id="navi-cat">';
if (cat_start > 1) {
dw += '' + cat_pre + ''
}
if ((cat_start + cat_numb - 1) < tt) {
dw += '' + cat_nex + ''
}
dw += '<span>' + cat_start;
if (cat_start != tt) {
dw += ' – ' + (cat_start + i - 1)
}
dw += ' / ' + tt + '</span>';
dw += '</div>';
document.getElementById('show-post').innerHTML = dw + '<style type="text/css">.cat-' + cat_class + ' a{background:#bbb!important;color:#fff!important}<\/style>'
}
function show_post(a, b, c) {
var d = document.getElementsByTagName('head')[0];
e = document.createElement('script');
e.type = 'text/javascript';
e.setAttribute('src', cat_home + '/feeds/posts/default/-/' + a + '?alt=json-in-script&start-index=' + b + '&max-results=' + cat_numb + '&callback=show_post2');
d.appendChild(e);
cat_name = a;
cat_start = parseInt(b), cat_class = c
}
function show_cat(a) {
var cat = a.feed.category;
cat = cat.filter(i => !["Label12","Label13"].includes(i.term));
dw = '';
dw += '<ul>';
for (var i = 0; i < cat.length - 1; i++) {
for (var j = i + 1; j < cat.length; j++) {
if (cat[i].term > cat[j].term) {
cat_hv = cat[i].term;
cat[i].term = cat[j].term;
cat[j].term = cat_hv
}
}
}
for (var i = 0; i < cat.length; i++) {
dw += '<li class="cat-' + i + '">';
dw += '<a href="" onclick="show_post(\'' + cat[i].term + '\',\'1\',\'' + i + '\');return false" title="';
dw += cat[i].term;
dw += '">';
dw += cat[i].term;
dw += '</a>';
dw += '</li>'
}
dw += '</ul>';
document.getElementById('show-cat').innerHTML = dw;
show_post(cat[0].term, 1);
}
document.write('<script type="text/javascript" src="' + cat_home + '/feeds/posts/default?alt=json-in-script&max-results=0&callback=show_cat"><\/script>');

Select a cell from the table and giving it unique class

I have 49 cells (7x7 rows/cols), and I'm trying to create one cell out of the 49 cells to be unique, as you can see when you run the snippet, the 49 cells have random numbers between 50 to 500, and one of these cells have Red color.
The problem I'm struggling with, I want that one cell to have Symbol (marking plate) like S or D for example instead of number, How i can achieve that?
var isCol = 0;
var board = [];
for (r = 0; r < 7; r++) {
var line = [];
for (c = 0; c < 7; c++) {
line.push(RandomGenerator(50, 500));
}
board.push(line);
}
function prs(c, r) {
showTable(c, r);
isCol = (isCol + 1) % 2;
}
function toColor(col, row, chosen_col, chosen_row) {
var ret = false;
switch (isCol) {
case 0:
if (row == chosen_row) {
ret = true;
}
break;
case 1:
if (col == chosen_col) {
ret = true;
}
break;
}
return ret;
}
function showTable(chosen_col, chosen_row) {
var str = "";
str += "<table border=1>";
for (row = 0; row < 7; row++) {
str += "<tr>";
for (col = 0; col < 7; col++) {
str += "<td onclick='prs(" + col + "," + row + ")'";
if (toColor(col, row, chosen_col, chosen_row)) {
str += " class='grn' ";
}
str += ">";
str += board[row][col];
str += "</td>";
}
str += "</tr>";
}
str += "</table>";
document.getElementById("ff").innerHTML = str;
}
function RandomGenerator(min, max) {
return Math.floor(Math.random() * (max - min) + min);
}
showTable(-1);
var getUnique = function(){
var tdElements = document.querySelectorAll('#ff td');
tdElements[
RandomGenerator(0, tdElements.length)
].classList.add('uniqueCell')
};
getUnique();
td{
border:2px solid black;
width:10px;
height:10px;
}
td:hover{background-color:lightgreen;}
.grn{
background-color:green;
color:white;
}
.uniqueCell {
background-color: tomato;
}
<div id="ff"></div>
It seems pretty easy as you have a class (uniqueCell) in the element. You can simply target the cell with the class (uniqueCell) and set the innerText or textContent property:
document.querySelector('.uniqueCell').textContent = 'S';
var isCol = 0;
var board = [];
for (r = 0; r < 7; r++) {
var line = [];
for (c = 0; c < 7; c++) {
line.push(RandomGenerator(50, 500));
}
board.push(line);
}
function prs(curr, c, r) {
showTable(curr, c, r);
isCol = (isCol + 1) % 2;
}
function toColor(col, row, chosen_col, chosen_row) {
var ret = false;
switch (isCol) {
case 0:
if (row == chosen_row) {
ret = true;
}
break;
case 1:
if (col == chosen_col) {
ret = true;
}
break;
}
return ret;
}
function showTable(c, chosen_col, chosen_row) {
var str = "";
str += "<table border=1>";
for (row = 0; row < 7; row++) {
str += "<tr>";
for (let col = 0; col < 7; col++) {
str += "<td onclick='prs(this, " + col + "," + row + ")'";
if (toColor(col, row, chosen_col, chosen_row)) {
if(c.textContent == board[row][col]){
str += " class=uniqueCell";
}
else str += " class='grn' ";
}
str += ">";
if(c.textContent == board[row][col]){
str += 'S';
}
else str += board[row][col];
str += "</td>";
}
str += "</tr>";
}
str += "</table>";
document.getElementById("ff").innerHTML = str;
}
function RandomGenerator(min, max) {
return Math.floor(Math.random() * (max - min) + min);
}
showTable(-1);
var getUnique = function(){
var tdElements = document.querySelectorAll('#ff td');
tdElements[
RandomGenerator(0, tdElements.length)
].classList.add('uniqueCell');
// update the text of the cell using the class
document.querySelector('.uniqueCell').textContent = 'S';
};
getUnique();
td{
border:2px solid black;
width:10px;
height:10px;
text-align: center;
}
td:hover{background-color:lightgreen;}
.grn{
background-color:green;
color:white;
}
.uniqueCell {
background-color: tomato;
}
<div id="ff"></div>

How to select a certain cell from a table

I have 14 generated cells.
How can I select a specific cell from the 14 cells and control it? I want only one cell to be unique, the rest to be how they are displayed in the code, normally.
var isCol = 0;
var board = [];
for (r = 0; r < 7; r++) {
var line = [];
for (c = 0; c < 7; c++) {
line.push(r);
}
board.push(line);
}
function prs(c, r) {
showTable(c, r);
isCol = (isCol + 1) % 2;
}
function toColor(col, row, chosen_col, chosen_row) {
var ret = false;
switch (isCol) {
case 0:
if (row == chosen_row) {
ret = true;
}
break;
case 1:
if (col == chosen_col) {
ret = true;
}
break;
}
return ret;
}
function showTable(chosen_col, chosen_row) {
var str = "";
str += "<table border=1>";
for (row = 0; row < 7; row++) {
str += "<tr>";
for (col = 0; col < 7; col++) {
str += "<td onclick='prs(" + col + "," + row + ")'";
if (toColor(col, row, chosen_col, chosen_row)) {
str += " class='grn' ";
}
str += ">";
str += RandomGenerator(50, 500);
str += "</td>";
}
str += "</tr>";
}
str += "</table>";
document.getElementById("ff").innerHTML = str;
}
function RandomGenerator(min, max) {
return Math.floor(Math.random() * (max - min) + min);
}
showTable(-1);
td {
border: 2px solid black;
width: 10px;
height: 10px;
}
td:hover {
background-color: lightgreen;
}
.grn {
background-color: green;
color: white;
}
<div id='ff'></div>
You can create a ID for that row
EG
<td id = "uniqueCell"> ... </td>
Then in your javascript you can do the following.
var uniqueCell = document.getElementById('uniqueCell');
then use that variable to do what you need to do

For Loop with two array in javascript

I am new in js and have this problem. I have two arrays and like to achieve this layout by using for loop. I do not know how to write this to achieve it. Here is my code. Please help.
var html ='';
var option = ['meal', 'drink'];
var option_type = ['big', 'medium', 'small', 'big', 'medium'];
for (var i in option){
for ( var j in option_type){
html += '<div>'+ option[i] + '</div>'+'<p>'+option_type[j]+'</p>';
}
}
.(class).html(html);
You can use for like:
var html = '';
var option = ['meal', 'drink'];
var option_type = ['big', 'medium', 'small'];
for (i = 0; i < option.length; i++) {
html += '<div>' + option[i] + '</div>'; //Add option here (header)
for (j = 0; j < option_type.length; j++) {
html += '<p>' + option_type[j] + '</p>'; //Add option_type
}
}
$('body').html(html);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
An object data structure is better for representing what you want (at least based on the screenshot)
var options = {
meal: ['big', 'medium', 'small'],
drink: ['big', 'medium']
}
var html = Object.keys(options).reduce((all, option) => {
var headerMarkup = `<div>${option}</div>`;
var itemsMarkup = options[option].map(item => `<p>${item}</p>`).join('');
return `${all}${headerMarkup}${itemsMarkup}`;
}, '');
You can do something like this:
var html ='';
var option = [
['meal', 'big', 'medium', 'small'],
['drink', 'big', 'medium' ]
];
for (var i = 0; i < option.length; i++){
var option_type = option[i];
html += '<div>' + option_type[0] + '</div>';
for(var j = 1; j < option_type.length; j++) {
html += '<span>' + option_type[j] + '</span>';
}
}
document.getElementById('container').innerHTML=html;
#container span{
display:inline-block;
margin-right:10px;
border:1px solid #333;
padding:10px;
}
<div id="container"></div>
this is the direct answer to how to use nested for loops. But if you want to vary the option_types for each option, you will probably want to use an object as suggested by scetiner
var html ='';
var option = ['meal', 'drink'];
var option_type = ['big', 'medium', 'small'];
for (var i in option){
html += '<div><h1>'+ option[i] + "<h1>";
for ( var j in option_type){
html += '<p>'+option_type[j]+'</p>';
}
html += '</div>';
}
document.getElementById('container').innerHTML = html;
#container{
}
h1{
}
#container p{
display:inline-block;
margin:10px;
border:1px solid #333;
min-width: 100px;
padding:10px;
}
<div id='container'></div>
option_type is useless and not logical, try something like this
var html ='';
var option = {
'meal': [
'big',
'medium',
'small'
],
'drink': [
'big',
'medium'
]
};
for (var key in option){
html += '<div>'+ key + '</div>'
for ( var j of option[key]){
html += '<p>'+j+'</p>';
}
}
.(class).html(html);
Followin you approach here a full example: https://jsfiddle.net/57q39xre/17/
The key is:
for (var i in parent){
//parent code
for ( var j in child){
//parent and child code
}
//parent code
}
Each parent will iterate each child.

How can I use jQuery to randomly select one column from each row?

I have dynamically created rows and columns with jQuery. Can anyone help me on how to select a random column from each row? So far here is how my code looks like;
$(document).ready(function(){
var canva = $("#board");
var gameHolder = "<div class='gHolder'>";
var rows = 7;
var cols = 10;
function boardSetUp(){
for(var i = 0; i < rows; i++){
var row = "<div class='row'>";
for(var j = 0; j < cols; j++){
var col = "<li class='col'>";
col += "</li>";
row += col;
}
row += "</div>";
gameHolder += row;
}
gameHolder += "</div>";
canva.html(gameHolder);
}
boardSetUp();
})
You can use a comibnation of Math.floor() and Math.random() to get an integer between 1 and the amount of columns (x) per row.
Math.floor (Math.random () * x) + 1
I simplified your given example and added a funtion to select one random column per row. For this example I dynamically add a class for each selected column.
$(document).ready (function () {
var rows = 7;
var cols = 10;
var gameHolder = '';
for (var i = 0; i < rows; i++) {
gameHolder += '<div class="row">';
for(var j = 0; j < cols; j++)
gameHolder += '<div class="col"></div>';
gameHolder += '</div>';
}
$("#board").html(gameHolder);
})
function select_cols () {
var canvas = $("#board");
//reset all columns
$('.col').removeClass ('selected');
//loop through every row
canvas.find ('.row').each (function (i) {
//count columns and select random one
var count = $(this).find ('.col').size (); // $(this) is the current row
var selected = Math.floor (Math.random () * count) + 1;
//get your selected column-element
var column = $(this).find ('.col:nth-child(' + selected + ')') // :nth-child(x) is a css-selector
//do something with it. for example add a class
column.addClass ('selected');
});
}
#board {
border: 1px solid #999;
}
.row {
display: flex;
}
.col {
flex-grow: 1;
height: 10px;
border: 1px solid #999;
}
.selected {
background-color: #958;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="board"></div>
<br>
<button onclick="select_cols ();">select random columns</button>
I see that you're asking for a random column for each row, but if you'd like just a random position on the game board, you could do something like this:
$(document).ready(function(){
var canva = $("#board");
var gameHolder = "<div class='gHolder'>";
var rows = 7;
var cols = 10;
function boardSetUp(){
for(var i = 0; i < rows; i++){
var row = "<div class='row'>";
for(var j = 0; j < cols; j++){
var col = "<li class='col' id='" + i + "-" + j + "'>";
col += "</li>";
row += col;
}
row += "</div>";
gameHolder += row;
}
gameHolder += "</div>";
canva.html(gameHolder);
}
boardSetUp();
function selectRandomLocation(){
var pos = $('#' + Math.floor(Math.random() * rows) + '-' + Math.floor(Math.random() * cols));
return pos;
}
})
you can use foreach and random ,
try :
var j = 0;
$("row").each(function(){
random_col = Math.floor(Math.random() * 10);
var i = 0;
$("li").each(function(){
if(random_col == i)
/* $(this) = your random col */
alert("the random col is a number "+i+" for col number "+j);
i++;
});
j++;
});

Categories

Resources