How to select a certain cell from a table - javascript

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

Related

how to get Different name for each td?

I need some help, what should I do so that all the rows have each one a different id for example:introdu1,introdu2,introdu3
var perrow = 1;
array.forEach((value, i) => {
myTable += `<td id="ore">${value}</td>`;
myTable += `<td id="introdu" > </td>`;
var next = i + 1;
if (next%perrow==0 && next!=array.length) { myTable += "</tr><tr>"; }
});
It is very easy you can use ${variable} like you do in ${value}
let array = ['r','4','6'];
let myTable = "";
var perrow = 1;
array.forEach((value, i) => {
var next = i + 1;
myTable += `<td id="ore${next}">${value}</td>`;
myTable += `<td id="introdu${next}" > </td>`;
if (next%perrow==0 && next!=array.length) { myTable += "</tr><tr>"; }
});
console.log(myTable);
td {
background : red;
}
Use a dynamically generated ID:
var perrow = 1;
var id = 1;
array.forEach((value, i) => {
myTable += `<td id="ore${id}">${value}</td>`;
myTable += `<td id="introdu${id++}" > </td>`;
var next = i + 1;
if (next % perrow == 0 && next != array.length) {
myTable += "</tr><tr>";
}
});

How to check hasClass in html tables

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");
});

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 can I calculate the average of the random numbers in a grid?

I have a random grid generator that asks how big you want the grid. If you input 5 it will produce a 5x5 grid with random numbers in it, or a 10x10 grid with random numbers etc.
I now need to take those random numbers once the grid is produced and display the average of the random numbers. I can't seem to get this part to work, because there are different numbers each time you generate a new grid.
var button = document.getElementById('gridSize');
button.onclick = function(e) {
result = document.getElementById('wrapper');
num = parseInt(document.getElementById('grid').value);
var str = "<table border='2'>";
for (row = 0; row < num; row++) {
str += "<tr>";
for (col = 0; col < num; col++) {
var randNumber = Math.floor(Math.random() * 100) + 1;
if (randNumber % 3 === 0) {
str += '<td style="background: red;">';
}
else if (randNumber % 2 === 0 && !randNumber % 3 === 0) {
str += '<td style="background: blue;">';
}
else {
str += "<td>";
}
str += randNumber + "</td>";
}
str += "</tr>";
}
str = str + "</table>";
result.innerHTML = str;
}
<form name="tablegen">
<input type="text" name="grid" id="grid"/>
<input name="generate" id="gridSize" type="button" value="Generate Grid!" onclick='createTable();'/>
</form>
<div id="wrapper"></div>
This is my code and I just can't seem to figure out how to go about this.
Here is a simple way, just accumulate the randNumber you calculated, then divide by the total number of cells.
var button = document.getElementById('gridSize');
button.onclick = function(e) {
result = document.getElementById('wrapper');
num = parseInt(document.getElementById('grid').value);
var avg = 0;
var str = "<table border='2'>";
for (row = 0; row < num; row++) {
str += "<tr>";
for (col = 0; col < num; col++) {
var randNumber = Math.floor(Math.random() * 100) + 1;
avg += randNumber;
if (randNumber % 3 === 0) {
str += '<td style="background: red;">';
}
else if (randNumber % 2 === 0 && !randNumber % 3 === 0) {
str += '<td style="background: blue;">';
}
else {
str += "<td>";
}
str += randNumber + "</td>";
}
str += "</tr>";
}
avg /= num*num;
str = str + "</table>" + "<span>Average is " + avg + "</span>";
result.innerHTML = str;
}
<form name="tablegen">
<input type="text" name="grid" id="grid"/>
<input name="generate" id="gridSize" type="button" value="Generate Grid!" onclick='createTable();'/>
</form>
<div id="wrapper"></div>
A couple of additions to what you gave us to start with.
var button = document.getElementById('gridSize');
var total = 0;
var divisor = 0;
button.onclick = function(e) {
result = document.getElementById('wrapper');
num = parseInt(document.getElementById('grid').value);
var str = "<table border='2'>";
for (row = 0; row < num; row++) {
str += "<tr>";
for (col = 0; col < num; col++) {
var randNumber = Math.floor(Math.random() * 100) + 1;
total = total+randNumber;
++divisor;
if (randNumber % 3 === 0) {
str += '<td style="background: red;">';
}
else if (randNumber % 2 === 0 && !randNumber % 3 === 0) {
str += '<td style="background: blue;">';
}
else {
str += "<td>";
}
str += randNumber + "</td>";
}
str += "</tr>";
}
str = str + "</table>";
result.innerHTML = str;
var average = total / divisor;
var averageSpan = document.getElementById('average');
averageSpan.innerText = average;
}
<form name="tablegen">
<input type="text" name="grid" id="grid"/>
<input name="generate" id="gridSize" type="button" value="Generate Grid!" onclick='createTable();'/>
</form>
Average: <span id="average"></span>
<div id="wrapper"></div>
Also a fiddle: https://jsfiddle.net/xpvt214o/775850/
Well, create a variable where you keep summing all generated random numbers.
At the end, get that number and divide by the area of the grid (the number user typed * the number user typed num*num)
Like below:
var button = document.getElementById('gridSize');
button.onclick = function(e) {
var total = 0;
result = document.getElementById('wrapper');
num = parseInt(document.getElementById('grid').value);
var str = "<table border='2'>";
for (row = 0; row < num; row++) {
str += "<tr>";
for (col = 0; col < num; col++) {
var randNumber = Math.floor(Math.random() * 100) + 1;
if (randNumber % 3 === 0) {
str += '<td style="background: red;">';
}
else if (randNumber % 2 === 0 && !randNumber % 3 === 0) {
str += '<td style="background: blue;">';
}
else {
str += "<td>";
}
total += parseInt(randNumber);
str += randNumber + "</td>";
}
str += "</tr>";
}
str = str + "</table>";
result.innerHTML = str;
console.log("Avg.: ", total/(num*num) || 0)
}
<form name="tablegen">
<input type="text" name="grid" id="grid"/>
<input name="generate" id="gridSize" type="button" value="Generate Grid!" onclick='createTable();'/>
</form>
<div id="wrapper"></div>
There are already some good answers. Here is a different approach. I also "cleaned up" the HTML and code a bit:
let button = document.getElementById("generatorButton");
button.onclick = function(e) {
document.getElementById("grid").innerHTML = createGrid();
document.getElementById("full-average").innerText = getGridAverage();
document.getElementById("mod3-average").innerText = getGridAverage(".mod3");
document.getElementById("mod2-average").innerText = getGridAverage(".mod2");
}
function createGrid()
{
gridSize = parseInt(document.getElementById('gridSize').value);
let str = "<table border='2'>";
for (let row = 0; row < gridSize; row++) {
str += "<tr>";
for (let col = 0; col < gridSize; col++) {
var randNumber = Math.floor(Math.random() * 100) + 1;
if (randNumber % 3 === 0) {
str += '<td class="mod3">';
}
else if (randNumber % 2 === 0) {
str += '<td class="mod2">';
}
else {
str += "<td>";
}
str += randNumber + "</td>";
}
str += "</tr>";
}
str = str + "</table>";
return str;
}
function getGridAverage(cssClass)
{
if (cssClass == undefined) cssClass = "";
let cells = document.querySelectorAll("#grid td" + cssClass);
if (cells.length > 0)
{
let sum = 0;
for (const cell of cells)
{
sum += parseInt(cell.innerHTML);
}
return sum / cells.length;
}
else
return 0;
}
.mod3 {
background-color: red;
}
.mod2 {
background-color: blue;
}
<form name="tablegen">
<input type="text" id="gridSize" placeholder="Enter grid size (e.g.: 5)" />
<input type="button" id="generatorButton" value="Generate Grid!" />
</form>
<div id="grid"></div>
<div>Full Average:<span id="full-average">n/a</span></div>
<div>Mod3 (red) Average:<span id="mod3-average">n/a</span></div>
<div>Mod2 (blue) Average:<span id="mod2-average">n/a</span></div>

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