Select a cell from the table and giving it unique class - javascript

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>

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 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

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

I want to display array elements in a table row such that each row contains 3 elements

Thanks for your answer. what if I have to display 3 in .I want to iterate the loop to display 3 elements in each row.
table= '<table>';
for(i=1;i<=arr.length;i++) {
table= '<tr>';
if(arr[i]==undefined)
{
table += '</tr>';
break;
}
else {
table+='<td>'+arr[i]+'</td>';
//document.write(arr[i] + ' ');
}
if(i%3 == 0) {
table += '</tr>';
//document.write('<br />');
}
}
table += '</table>';
document.write(table);
var arr=['apple','boy','cat','dog','egg','fish','gum','gun','hat','ink','jug','kite','lamb','man'];
for(var i=0;i<arr.length;i+=3){
var row = [];
row.push(arr[i] || '' );
row.push(arr[i+1] || '' );
row.push(arr[i+2] || '' );
row.push("<br>");
document.write(row.join(" "))
}
You challenged me and... okay that is easy and it's easy to read:
var arr = ['apple','boy','cat','dog','egg','fish','gum','gun','hat','ink','jug','kite','lamb','man'];
var html = [];//like a string builder
html.push('<table>');
for(let i = 0; i < arr.length; i += 3){
html.push('<tr>');
html.push('<td>', arr[i] ,'</td>');
html.push('<td>', arr[i + 1], '</td>');
html.push('<td>', arr[i + 2], '</td>');
html.push('</tr>');
}
html.push('</table>');
document.write(html.join(''));
td{
border: 1px solid black;
}
Try this one:
var arr=['apple','boy','cat','dog','egg','fish','gum','gun','hat','ink','jug','kite','lamb','man'];
for(i=0;i<arr.length;i++) {
if(i != 0 && i%3 === 0) {
document.write('<br />');
}
if(arr[i]==undefined)
break;
else {
document.write(arr[i] + ' ');
}
}

Categories

Resources