highlighting the new drawn number - javascript

I would like to specify my page and add that only the latest generated number is highlighted. The current page highlights each number and I would like it to highlight only the latest number in the table and then go out, i.e. when the number 12 is drawn, the cell with the number 12 will be highlighted, and if the number is drawn 55 then 12 goes out and 55 lights up
jQuery(function ($) {
var bingo = {
selectedNumbers: [],
generateRandom: function () {
var min = 1; //Liczba początkowa
var max = 89; //Liczba końcowa
var random = Math.floor(Math.random() * (max - min + 1)) + min;
return random;
},
generateNextRandom: function () {
if (bingo.selectedNumbers.length > 88) {
alert("Koniec");
return 0;
}
var random = bingo.generateRandom();
while ($.inArray(random, bingo.selectedNumbers) > -1) {
random = bingo.generateRandom();
}
bingo.selectedNumbers.push(random);
return random;
},
};
$("td").each(function () {
var concatClass = this.cellIndex + "" + this.parentNode.rowIndex;
var numberString = parseInt(concatClass, 10).toString();
$(this)
.addClass("cell" + numberString)
.text(numberString);
$(".cell" + numberString).attr("CellValue", numberString);
});
$("#btnGenerate").click(function () {
var random = bingo.generateNextRandom().toString();
$(".bigNumberDisplay span").text(random);
$("td.cell" + random).addClass("selected");
$("td").each(function () {
if ($(this).attr("CellValue") === random) {
$(this).css("background-color", "yellow");
}
});
});
window.onbeforeunload = function (e) {
e = e || window.event;
var returnString = "Are you sure?";
if (e) {
e.returnValue = returnString;
}
return returnString;
};
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="pl">
<head>
<title> Bingo</title>
<link href="style.css" rel="stylesheet" />
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.js"></script>
<script src="./index.js"></script>
</head>
<body>
<div class="container">
<div class="bigNumberDisplay">
<span>0</span>
</div>
<div>
<input id="btnGenerate" type="button" value="Wylosuj numer stolika" />
</div>
<br />
<div class="numbersTable">
<table>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
</table>
</div>
<br />
</div>
</body>
</html>
div {
text-align: center;
}
.bigNumberDisplay {
font-size: 6em;
}
.numbersTable {
font-size: 1.6em;
}
table {
margin-left: auto;
margin-right: auto;
}
table,
tr,
td {
border-collapse: collapse;
border: solid 1px #999;
}
td {
min-width: 100px;
color: #fff;
}
td.selected {
color: #000000;
}
a basic design in which each number highlights

You can do it like this: Instead of setting the inline style background-color: yellow, add a class to the newly appended cell. When the generate button is clicked, remove this class from all cells and add it only to the newly appended cell.
jQuery(function($) {
var bingo = {
selectedNumbers: [],
generateRandom: function() {
var min = 1; //Liczba początkowa
var max = 89; //Liczba końcowa
var random = Math.floor(Math.random() * (max - min + 1)) + min;
return random;
},
generateNextRandom: function() {
if (bingo.selectedNumbers.length > 88) {
alert("Koniec");
return 0;
}
var random = bingo.generateRandom();
while ($.inArray(random, bingo.selectedNumbers) > -1) {
random = bingo.generateRandom();
}
bingo.selectedNumbers.push(random);
return random;
},
};
$("td").each(function() {
var concatClass = this.cellIndex + "" + this.parentNode.rowIndex;
var numberString = parseInt(concatClass, 10).toString();
$(this)
.addClass("cell" + numberString)
.text(numberString);
$(".cell" + numberString).attr("CellValue", numberString);
});
$("#btnGenerate").click(function() {
var random = bingo.generateNextRandom().toString();
$(".bigNumberDisplay span").text(random);
$("td.cell" + random).addClass("selected");
$("td.active").removeClass("active");
$("td").each(function() {
if ($(this).attr("CellValue") === random) {
$(this).addClass("active");
}
});
});
window.onbeforeunload = function(e) {
e = e || window.event;
var returnString = "Are you sure?";
if (e) {
e.returnValue = returnString;
}
return returnString;
};
});
.active {
background-color:yellow;
}
div {
text-align: center;
}
.bigNumberDisplay {
font-size: 6em;
}
.numbersTable {
font-size: 1.6em;
}
table {
margin-left: auto;
margin-right: auto;
}
table,
tr,
td {
border-collapse: collapse;
border: solid 1px #999;
}
td {
min-width: 100px;
color: #fff;
}
td.selected {
color: #000000;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="pl">
<head>
<title> Bingo</title>
<link href="style.css" rel="stylesheet" />
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.js"></script>
<script src="./index.js"></script>
</head>
<body>
<div class="container">
<div class="bigNumberDisplay">
<span>0</span>
</div>
<div>
<input id="btnGenerate" type="button" value="Wylosuj numer stolika" />
</div>
<br />
<div class="numbersTable">
<table>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
</table>
</div>
<br />
</div>
</body>
</html>

I would use a CSS class to make the highlighted number yellow:
.highlight {
background-color: yellow;
}
I would add that class to the cell that you want to highlight. It looks like you are looping through all td elements and finding the one with the right CellValue attribute. You can select that element using CSS selectors instead.
So try replacing this code:
$("td").each(function () {
if ($(this).attr("CellValue") === random) {
$(this).css("background-color", "yellow");
}
});
With:
$('.highlight').removeClass('highlight');
$('td[CellValue="' + random + '"]').addClass('highlight');
This would also remove the highlight class from the cell you first selected.
This is using CSS attribute selectors to target the correct cell. You can read more about CSS attribute selectors here: https://developer.mozilla.org/en-US/docs/Web/CSS/Attribute_selectors

The accepted answer is great. I just thought it would be fun to make a concise version of this with rando.js and jquery.
var ROWS = 10;
var COLS = 9;
$(document).ready(function() {
var htmlToAdd = "";
for (var i = 0; i < ROWS; i++) {
htmlToAdd += "<tr>";
for (var j = 0; j < COLS; j++) htmlToAdd += "<td style=\"width:" + 100 / COLS + "%;\">" + (i + (COLS + 1) * j) + "</td>";
htmlToAdd += "</tr>";
}
$("table").html(htmlToAdd);
});
function showNext() {
$(".highlighted").removeClass("highlighted");
if (pick = rando($("td").not(".shown")).value || false) $("#result").text(pick.addClass("shown").addClass("highlighted").text());
}
body{ padding:50px; text-align:center; }
#result{ font-size:96px; }
table{ border-collapse:collapse; width:100%; }
td{ color:transparent; border:1px solid #999; text-align:center; font-size:25px; }
td.shown{ color:black; }
td.highlighted{ background:yellow; }
button{ margin:20px 0px; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://randojs.com/1.0.0.js"></script>
<div id="result">0</div>
<button onclick="showNext();">Show next</button>
<table></table>

Related

How to check Conway's Game Of Life Code - Glider Gun

I have written code of Conway's Game Of Life with JS and I'm pretty sure something is wrong. I'm trying to imitate Gosper glider gun, but even when starting with the right pattern, i can't built any gliders.
I wrote an interface with buttons to toggle, stop and clear the game, and also a button that initializes the game to the pattern of the glider gun
I couldn't fit the table in full into the question here - need to add extra rows for it to work
var main = document.getElementById("main");
document.getElementById("toggle").setAttribute("onclick", "toggleTable()");
document.getElementById("stop").setAttribute("onclick", "stopTable()");
document.getElementById("setGun").setAttribute("onclick", "setGun()");
document.getElementById("clear1").setAttribute("onclick", "clear1()");
for (var i = 0; i < main.rows.length; i++) {
var currow = main.rows[i];
for (var f = 0; f < currow.cells.length; f++)
currow.cells[f].setAttribute("onclick", "changeColor(this)");
}
function changeColor(item) {
item.classList.toggle("clicked");
}
function clear1() {
for (var i = 0; i < main.rows.length; i++) {
var currow = main.rows[i];
for (var f = 0; f < currow.cells.length; f++)
main.rows[i].cells[f].classList.remove("clicked");
}
}
function setGun() {
changeColor(main.rows[3].cells[36]);
changeColor(main.rows[3].cells[37]);
changeColor(main.rows[4].cells[36]);
changeColor(main.rows[4].cells[37]);
changeColor(main.rows[1].cells[26]);
changeColor(main.rows[2].cells[26]);
changeColor(main.rows[2].cells[24]);
changeColor(main.rows[3].cells[23]);
changeColor(main.rows[3].cells[22]);
changeColor(main.rows[4].cells[23]);
changeColor(main.rows[4].cells[22]);
changeColor(main.rows[5].cells[23]);
changeColor(main.rows[5].cells[22]);
changeColor(main.rows[6].cells[24]);
changeColor(main.rows[6].cells[26]);
changeColor(main.rows[7].cells[26]);
changeColor(main.rows[5].cells[2]);
changeColor(main.rows[5].cells[3]);
changeColor(main.rows[6].cells[2]);
changeColor(main.rows[6].cells[3]);
changeColor(main.rows[3].cells[15]);
changeColor(main.rows[3].cells[14]);
changeColor(main.rows[4].cells[13]);
changeColor(main.rows[5].cells[12]);
changeColor(main.rows[6].cells[12]);
changeColor(main.rows[7].cells[12]);
changeColor(main.rows[8].cells[13]);
changeColor(main.rows[9].cells[14]);
changeColor(main.rows[9].cells[15]);
changeColor(main.rows[6].cells[16]);
changeColor(main.rows[4].cells[17]);
changeColor(main.rows[8].cells[17]);
changeColor(main.rows[5].cells[18]);
changeColor(main.rows[6].cells[18]);
changeColor(main.rows[7].cells[18]);
changeColor(main.rows[6].cells[19]);
}
function calcNeigh(row, cell) {
var countNeigh = 0;
if ((row - 1 != -1 && row - 1 < main.rows.length && cell - 1 != -1 && cell - 1 < main.rows[row].cells.length) && main.rows[row - 1].cells[cell - 1].classList.contains("clicked"))
countNeigh++
if ((row - 1 != -1 && row - 1 < main.rows.length) && main.rows[row - 1].cells[cell].classList.contains("clicked"))
countNeigh++
if ((row - 1 != -1 && row - 1 < main.rows.length && cell + 1 < main.rows[row].cells.length) && main.rows[row - 1].cells[cell + 1].classList.contains("clicked"))
countNeigh++
if ((cell - 1 != -1) && main.rows[row].cells[cell - 1].classList.contains("clicked"))
countNeigh++
if ((cell + 1 != -1 && cell + 1 < main.rows[row].cells.length) && main.rows[row].cells[cell + 1].classList.contains("clicked"))
countNeigh++
if ((row + 1 < main.rows.length && cell - 1 != -1) && main.rows[row + 1].cells[cell - 1].classList.contains("clicked"))
countNeigh++
if ((row + 1 < main.rows.length) && main.rows[row + 1].cells[cell].classList.contains("clicked"))
countNeigh++
if ((row + 1 < main.rows.length && cell + 1 < main.rows[row].cells.length) && main.rows[row + 1].cells[cell + 1].classList.contains("clicked"))
countNeigh++
return countNeigh;
}
function isAlive(i, f) {
if (main.rows[i].cells[f].classList.contains("clicked"))
return true;
else return false;
}
function liveOrDie(neigh, i, f) {
if (isAlive(i, f)) {
if (neigh > 3 || neigh < 2)
main.rows[i].cells[f].classList.remove("clicked");
}
else if (neigh == 3)
main.rows[i].cells[f].classList.add("clicked");
}
var run;
function toggleTable() {
run = setInterval(function () {
for (var i = 0; i < main.rows.length; i++) {
var currow = main.rows[i];
for (var f = 0; f < currow.cells.length; f++) {
liveOrDie(calcNeigh(i, f), i, f);
}
}
}, 200);
}
function stopTable() {
clearInterval(run);
}
#main td {
width: 20px;
height: 20px;
border: 1px solid silver;
}
#main {
text-align: center;
margin: auto;
}
.clicked {
background-color: black;
}
#toggle {
width: 200px;
height: 50px;
background-color: navy;
}
#stop {
width: 200px;
height: 50px;
background-color: green;
}
#setGun {
width: 200px;
height: 50px;
background-color: orchid;
}
#clear1 {
width: 200px;
height: 50px;
background-color: white;
border: 1px solid black;
}
<table id="main">
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
</table>
<div id="toggle">toggle</div>
<div id="stop">stop</div>
<div id="setGun">setGun</div>
<div id="clear1">clear</div>
The problem is that your code updates the cells, while their previous state is still needed to calculate the next state of some neighboring cells, so the calculation for those cells will be wrong.
You need to make sure that all calculations (neigh) are done on a snapshot of the "generation" and not on a mutating state.
Other remarks on your code:
Don't use the DOM to maintain the state of the game. Instead maintain the state in an array data structure, and only write to the DOM (not read from it).
Don't set "onclick" attributes. Instead use addEventListener
Don't use the pattern if <boolean expression> return true; else return false (like you did in isAlive). Instead, just return the boolean expression.
Avoid code repetition, like in setGun, where you can make the logic more data-driven: put the involved values in an array, and then loop over that array to initialise the game
Here is what I would make of your code:
const main = document.getElementById("main");
// Create a memory data structure for the real state of the game
const rowCount = 15, colCount = 50;
let grid = Array.from({length: rowCount}, row => Array(colCount).fill(false));
// Build table dynamically to save repetition in static HTML
main.innerHTML = ("<tr>" + "<td><\/td>".repeat(colCount) + "</tr>").repeat(rowCount);
document.getElementById("toggle").addEventListener("click", startAnimation);
document.getElementById("stop").addEventListener("click", stopAnimation);
document.getElementById("setGun").addEventListener("click", setGun);
document.getElementById("clear").addEventListener("click", clear);
main.addEventListener("click", e => changeColor(e.target.cellIndex, e.target.parentNode.rowIndex));
// Define constant for some configuration:
const GUN = `
--------------------------X
------------------------X-X
--------------XX------XX------------XX
-------------X---X----XX------------XX
--XX--------X-----X---XX
--XX--------X---X-XX----X-X
------------X-----X-------X
-------------X---X
--------------XX`;
// This function alone is responsible for any output
function display() {
grid.forEach((row, y) =>
row.forEach((cell, x) =>
main.rows[y].cells[x].classList.toggle("clicked", cell)
)
);
}
function changeColor(x, y) {
grid[y][x] = !grid[y][x];
display();
}
function clear() {
stopAnimation();
grid.forEach(row => row.fill(false));
display();
}
function setFromString(s) {
clear();
s.match(/\S+/g).forEach((line, y) => {
grid[y].forEach((_, x, row) => row[x] = line[x] == "X")
});
display();
}
function setGun() {
setFromString(GUN);
}
function calcNeigh(x, y) {
return [[x-1,y-1], [x,y-1], [x+1,y-1], [x-1,y], [x+1,y], [x-1,y+1], [x,y+1], [x+1,y+1]]
.reduce((sum, [x, y]) => sum + isAlive(x, y), 0);
}
function isAlive(x, y) {
return !!grid[y]?.[x];
}
function liveOrDie(neigh, x, y) {
return neigh == 2 ? isAlive(x, y) : neigh == 3;
}
function nextGeneration() {
// grid is updated with a new 2D array, so there is no interference!
grid = grid.map((row, y) =>
row.map((cell, x) => liveOrDie(calcNeigh(x, y), x, y))
);
display();
}
let run;
function startAnimation() {
stopAnimation(); // Make sure to first stop the current timer
run = setInterval(nextGeneration, 200);
}
function stopAnimation() {
clearInterval(run);
}
table { border-collapse: collapse }
#main td {
width: 8px;
height: 8px;
border: 1px solid silver;
}
#main {
text-align: center;
margin: auto;
}
.clicked { background-color: black; }
button {
width: 100px;
height: 30px;
}
#toggle { background-color: cyan; }
#stop { background-color: green; }
#setGun { background-color: orchid; }
#clear { background-color: white; }
<table id="main"></table>
<button id="toggle">Start</button>
<button id="stop">Stop</button>
<button id="setGun">Set Gun</button>
<button id="clear">Clear</button>

Copy, Drag and drop table cells only within a table column - JS

I have a table and I can only drag/drop cells across different columns. However, I want the functionality to copy the cell while dragging and dropping it in the same column. If a column already has a value, we need to replace that value with the pasted value. Please advice.
This is my code:
$(document).ready(function() {
$('.event-1').on("dragstart", function(event) {
var dt = event.originalEvent.dataTransfer;
dt.setData('Text', $(this).attr('id'));
});
$('table td').on("dragenter dragover drop", function(event) {
event.preventDefault();
if (event.type === 'drop') {
var data = event.originalEvent.dataTransfer.getData('Text', $(this).attr('col-1'));
de = $('#' + data).detach();
de.appendTo($(this));
};
});
$('.event-2').on("dragstart", function(event) {
var dt = event.originalEvent.dataTransfer;
dt.setData('Text', $(this).attr('id'));
});
$('table td').on("dragenter dragover drop", function(event) {
event.preventDefault();
if (event.type === 'drop') {
var data = event.originalEvent.dataTransfer.getData('Text', $(this).attr('col-2'));
de = $('#' + data).detach();
de.appendTo($(this));
};
});
})
table th,
table td {
height: 30px;
width: 200px;
}
table span {
display: block;
background-color: #09C;
height: 100%;
width: 100%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="#our_table" border="1">
<tr>
<th>head1</th>
<th>head1</th>
<th>head1</th>
</tr>
<tr>
<td><span class="event-1" id="col-1" draggable="true">aaa</span></td>
<td></td>
<td></td>
</tr>
<tr>
<td>sample</td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td><span class="event-2" id="col-2" draggable="true">bbb</span></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
</table>
Any help is appreciated.
Whenever any element is drag you can get index() of tdand tr tag and save them in setData() method . Now , when you are going to drop that element check if the td(where you need to drop) and td(from where span is taken) are same if they match simply get the data which is set in setData method using that data we can detach() that element and append to new td .
Demo Code :
$(document).on("dragstart", 'td span', function(event) {
var dt = event.originalEvent.dataTransfer;
dt.setData('Text', $(this).closest("td").index() + " , " + $(this).closest("tr").index()); //save index of td & tr
});
$('table td').on("dragenter dragover drop", function(event) {
event.preventDefault();
var index_ = $(this).index() //get index of td where we are dropping..
if (event.type === 'drop') {
var data = event.originalEvent.dataTransfer.getData('Text');
var new_data = data.split(",") //get data which is set
//check if the index of td from where span is taken and td where span is to drop is same..
if (new_data[0] == index_) {
$(this).text("") //clear if any text before...
de = $(`tr:eq(${new_data[1]}) td:eq(${new_data[0]}) span`).clone() //detach() //get that element
$(de[0]).appendTo($(this)); //append
}
};
});
table th,
table td {
height: 30px;
width: 200px;
}
table span {
display: block;
background-color: #09C;
height: 100%;
width: 100%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<table id="#our_table" border="1">
<tr>
<th>head1</th>
<th>head1</th>
<th>head1</th>
</tr>
<tr>
<td><span draggable="true">aaa</span></td>
<td></td>
<td></td>
</tr>
<tr>
<td>sample</td>
<td></td>
<td><span draggable="true">ccc</span></td>
</tr>
<tr>
<td></td>
<td><span draggable="true">bbb</span></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
</table>

how can i put <td> on table cells?

First I made a table that have date titles in different format such as number of the gregorian date and name of the days of the Week and number of the persian date.
I want to color them when I select some cells and display them as a cell where text can be written inside such as below image:
![The desired table photo][1]
please help me to edit codes for create a table such as top image.
The table I made is as follows:
let jyear = moment().locale('fa').format('YYYY');
let jmonth = moment().locale('fa').format('M');
console.log("jyear", jyear);
console.log("jmonth", jmonth);
var d = new Date();
var months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
document.getElementById("EN-Year").innerHTML = d.getFullYear();
document.getElementById("EN-Month").innerHTML = months[d.getMonth()] + '-' + months[d.getMonth() + 1];
document.getElementById("shamsi_year").innerHTML = jyear;
document.getElementById("shamsi_month").innerHTML = moment().locale('fa').format('jMMMM');
document.getElementById("shamsi_month2").innerHTML = moment().locale('fa').format('jMMMM');
renderHeaderGrid(jyear, jmonth);
function renderHeaderGrid(jyear, jmonth) {
let jDate = moment.from(`${jyear}/${jmonth}/01`, 'fa', 'YYYY/MM/DD');
jDate = jDate.locale("fa");
let daysInMonth = jDate.daysInMonth();
let miladi_date = jDate.locale("en");
for (let i = 0; i < daysInMonth; i++) {
let miladiDayNameInWeek = miladi_date.format("dd"); //miladi day name of weeek
let miladiDayInMonth = miladi_date.format("DD"); //miladi day num
let shamsiDayInMonth = jDate.format("jDD"); //shamsi day num
let th_week_name = document.createElement("th");
let th_day_num = document.createElement("th");
let th_shamsi_day_num = document.createElement("th");
th_week_name.innerText = miladiDayNameInWeek;
th_day_num.innerText = miladiDayInMonth;
th_shamsi_day_num.innerText = shamsiDayInMonth;
document.getElementById("tr_days_name").append(th_week_name);
document.getElementById("tr_days_num").append(th_day_num);
document.getElementById("tr_days_shamsi_num").append(th_shamsi_day_num);
miladi_date.add(1, "d");
}
}
* {
direction: rtl;
}
table,
th,
td {
border: 1px solid black;
border-collapse: collapse;
position: relative;
}
.table {
width: 100%;
}
.month {
background-color: orange;
}
.place {
background-color: rgb(77, 207, 77);
}
.other,
.title {
background-color: rgb(141, 140, 140);
}
<table id="ttt" class="table" border="1" summary="This table gives some statistics about fruit
flies: average height and weight, and percentage
with red eyes (for both males and females).">
<caption>
<EM>A test table with merged cells</EM>
</caption>
<tr>
<th class="title" colspan="34"></th>
</tr>
<tr id="tr_days_name">
<th colspan="4">DAY</th>
</tr>
<tr id="tr_days_num" colspan="2">
<th id="EN-Year" colspan="2"></th>
<th id="EN-Month" class="month" colspan="2"></th>
</tr>
<tr rowspan="1" colspan="2" id="tr_days_shamsi_num">
<th id="shamsi_year" colspan="2"></th>
<th id="shamsi_month" class="month" colspan="2"></th>
</tr>
<tr id="firstplace">
<th id="shamsi_month2" colspan="2" rowspan="6"></th>
<th class="place" colspan="2"></th>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<th class="place" colspan="2"></th>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<th class="place" colspan="2"></th>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<th class="place" colspan="2"></th>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<th class="place" colspan="2"></th>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<th class="other" colspan="2"></th>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
</table>
<script src="https://unpkg.com/jalali-moment/dist/jalali-moment.browser.js"></script>
Hope this gives you an idea:
const cells = document.querySelectorAll(".cell");
cells.forEach((cell, i) => {
cell.addEventListener("click", () => {
cell.innerHTML = `<input type="text" id="cell-input_${i}">`
const cellInput = document.querySelector(`#cell-input_${i}`)
cellInput.focus()
cellInput.addEventListener("blur", () => {
cell.innerHTML = cellInput.value
});
});
});
.cell {
border: 1px solid black;
height: 20px;
min-width: 20px;
}
<table>
<tr>
<td class="cell"></td>
<td class="cell"></td>
<td class="cell"></td>
<td class="cell"></td>
<td class="cell"></td>
</tr>
</table>

Navigate through table TR with onkeydown or onkeyup

This is my current code:
Here I run some code and highlight the table row when the user clicks on the table row.
$("#orders tr").click(function() {
$(this).addClass('selected').siblings().removeClass('selected');
value = $(this).find('td:first').html();
});
table {
float: left;
border: 1px solid black;
border-collapse: collapse;
border-color: #a0a0a0ad;
}
table td {
padding: 5px;
}
table th {
background: #dcdcdc;
}
table tr {
height: 29px;
}
.selected {
background-color: #008cb9;
color: #FFF;
}
#orders {
width: 100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table name="orders" id="orders" border="1">
<thead>
<th>ID</th>
<th>Datum</th>
<th>Betaling</th>
</thead>
<tbody>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
</tbody>
</table>
I would like to be able to navigate through the table rows with upkey and downkey instead of clicking the table row; as well as call the method.
How am I able to do this?
You could add an event listner on the keydown then check if UP/Down keys are pressed and move the selected class to the next or previous tr :
$("#orders tr").click(function() {
$(this).addClass('selected').siblings().removeClass('selected');
value = $(this).find('td:first').html();
});
$(document).on('keydown', function(e) {
e.preventDefault();
if (e.which == 38) {
$('.selected').prev('tr').addClass('selected').siblings().removeClass('selected');
} else if (e.which == 40) {
$('.selected').next('tr').addClass('selected').siblings().removeClass('selected');
}
$('html, body').scrollTop($('.selected').offset().top - 100);
/*$('.selected')[0].scrollIntoView({
behavior: "smooth",
block: "end"
});*/
});
table {
float: left;
border: 1px solid black;
border-collapse: collapse;
border-color: #a0a0a0ad;
}
table td {
padding: 5px;
}
table th {
background: #dcdcdc;
}
table tr {
height: 29px;
}
.selected {
background-color: #008cb9;
color: #FFF;
}
#orders {
width: 100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table name="orders" id="orders" border="1">
<thead>
<th>ID</th>
<th>Datum</th>
<th>Betaling</th>
</thead>
<tbody>
<tr class='selected'>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
</tbody>
</table>
Here are the steps to achieve this.
Step-1. Track the keydown event on document
Step-2. Check for keyCode==38(up arrow) and keyCode==40(down arrow)
Step-3. If true add addClass('selected') on tr and remove from siblings() by removeClass('selected')
$("#orders tr").click(function() {
$(this).addClass('selected').siblings().removeClass('selected');
value = $(this).find('td:first').html();
});
$(document).on('keydown', function(e) {
e.preventDefault();
if (e.keyCode== 38) {
$('.selected').prev('tr').addClass('selected').siblings().removeClass('selected');
} else if (e.keyCode== 40) {
$('.selected').next('tr').addClass('selected').siblings().removeClass('selected');
}
});
table {
float: left;
border: 1px solid black;
border-collapse: collapse;
border-color: #a0a0a0ad;
}
table td {
padding: 5px;
}
table th {
background: #dcdcdc;
}
table tr {
height: 29px;
}
.selected {
background-color: #008cb9;
color: #FFF;
}
#orders {
width: 100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table name="orders" id="orders" border="1">
<thead>
<th>ID</th>
<th>Datum</th>
<th>Betaling</th>
</thead>
<tbody>
<tr class='selected'>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
</tbody>
</table>
$("#orders tr").click(function() {
$(this).addClass('selected').siblings().removeClass('selected');
value = $(this).find('td:first').html();
/// my code to show data and stuff
//////////////////////////
});
$('body').keyup(function(e) {
e.preventDefault();
if ($('.selected').length == 0) {
$($('tr')[1]).addClass('selected')
return;
}
if (e.which == 38) {
$('.selected').prev('tr').addClass('selected').siblings().removeClass('selected');
}
if (e.which == 40) {
$('.selected').next('tr').addClass('selected').siblings().removeClass('selected');
}
})
table {
float: left;
border: 1px solid black;
border-collapse: collapse;
border-color: #a0a0a0ad;
}
table td {
padding: 5px;
}
table th {
background: #dcdcdc;
}
table tr {
height: 29px;
}
.selected {
background-color: #008cb9;
color: #FFF;
}
#orders {
width: 100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table name="orders" id="orders" border="1">
<thead>
<th>ID</th>
<th>Datum</th>
<th>Betaling</th>
</thead>
<tbody>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
</tbody>
</table>
You can use the code as above!

How to get random numbers in a table cell in html using javascript

I want to generate number "1" in random cells from my table. There is a game like: you will select a table by pressing a button, after press play. When you will press play I want to put random the number "1" but not in all cells. (e.g: if table is 8x8, put 8 of "1" in the table, if table is 6x6, put 6 of "1" in the table and so on...) I create 3 tables in html and put them hidden with javascript.
Now I want some hints, some help from you guys. Thank you! Here is my code:
//Variables
var button1 = document.getElementById('button1');
var button2 = document.getElementById('button2');
var button3 = document.getElementById('button3');
var backBtn = document.getElementById('back-btn');
var playBtn = document.getElementById('play-btn');
var sixTable = document.getElementById('sixXsix');
var eightTable = document.getElementById('eightXeight');
var steenTable = document.getElementById('steen');
//Visibility starter
sixTable.style.display = 'none';
eightTable.style.display = 'none';
steenTable.style.display = 'none';
backBtn.style.display = 'none';
playBtn.style.display = 'none';
//Buttons function
button1.onclick = function() {
var six = document.getElementById('sixXsix');
var eight = document.getElementById('eightXeight');
var steen = document.getElementById('steen');
if (six.style.display === 'none') {
six.style.display = 'block';
eight.style.display = 'none';
steen.style.display = 'none';
button1.style.display = 'none';
button2.style.display = 'none';
button3.style.display = 'none';
backBtn.style.display = 'block';
playBtn.style.display = 'block';
}
}
button2.onclick = function() {
var six = document.getElementById('sixXsix');
var eight = document.getElementById('eightXeight');
var steen = document.getElementById('steen');
if (eight.style.display === 'none') {
six.style.display = 'none';
eight.style.display = 'block';
steen.style.display = 'none';
button1.style.display = 'none';
button2.style.display = 'none';
button3.style.display = 'none';
backBtn.style.display = 'block';
playBtn.style.display = 'block';
}
}
button3.onclick = function() {
var six = document.getElementById('sixXsix');
var eight = document.getElementById('eightXeight');
var steen = document.getElementById('steen');
if (steen.style.display === 'none') {
six.style.display = 'none';
eight.style.display = 'none';
steen.style.display = 'block';
button1.style.display = 'none';
button2.style.display = 'none';
button3.style.display = 'none';
backBtn.style.display = 'block';
playBtn.style.display = 'block';
}
}
backBtn.onclick = function() {
sixTable.style.display = 'none';
eightTable.style.display = 'none';
steenTable.style.display = 'none';
backBtn.style.display = 'none';
playBtn.style.display = 'none';
button1.style.display = 'block';
button2.style.display = 'block';
button3.style.display = 'block';
}
playBtn.onclick = function() {
}
<div id="buttons">
<button id="button1">6x6 Table</button>
<button id="button2">8x8 Table</button>
<button id="button3">16x16 Table</button>
<button id="back-btn">Back</button>
<button id="play-btn">Play</button>
</div>
<div id="table">
<div id="sixXsix">
<table>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
</table>
</div>
<div id="eightXeight">
<table>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
</table>
</div>
<div id="steen">
<table>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
</table>
</div>
</div>
This below code uses jquery to generate random numbers between 1 and the number of cells and then places a 1 in the corresponding cell.
If any of it is not clear, let me know.
Hope this helps.
$('#playBtn').on('click', function() {
var cellsCount = $('#table1 td').length;
var rows = $('#table1 tr').length;
var usedCells = [];
if (rows != $("#table1 tr:first-child td").length) {
alert("The grid is not a square, I dont know how many cells to mark.");
return;
}
// empty all cells first
$("#table1 td").empty();
$("#table1 td").css("background-color", "white");
// generate random numbers between 1 and the number of cells available
// (no duplicates)
while (usedCells.length < rows) {
randCell = Math.floor(Math.random() * cellsCount);
if (usedCells.indexOf(randCell) == -1) {
usedCells.push(randCell);
}
}
// for each number generate, color the cell and add the "1"
$.each(usedCells, function(index, value) {
cell = "#table1 td:eq(" + value + ")";
$(cell).html("1");
$(cell).css("background-color", "red");
});
});
td {
border: 1px solid black;
height: 25px;
width: 25px;
text-align: center;
background-color: #fff;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<button id="playBtn">Play</button>
<br>
<table id="table1">
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
</table>
This snippet uses a templating method (interpolate) to create a nXn table containing n random cells with value 1. See this git-repo for usage of interpolate.
(function () {
String.prototype.interpolate = function (tokens) {
return interpolate(this, tokens);
};
document.querySelector("#buttons")
.addEventListener('click', createTable);
document.querySelector("#button1").click();
function createTable(evt) {
const origin = evt.target;
if ( !/button/i.test(origin.nodeName)) { return; }
const size = origin.getAttribute('data-table')
.split('x')
.reduce(function (a, b, i) {
i == 1 ? a.rows = +b : a.cols = +b; return a;
}, {} );
size.totalCells = size.rows * size.cols;
const fillCells = getUniqueRandomValues(size.cols, size.totalCells);
let cellCount = 0;
const rowCells = () => '<td{hasValue}> </td>'
.interpolate( Array(size.rows).join(",").split(",")
.map( () => {
return {
hasValue: fillCells.indexOf(cellCount++) > -1
? " class=\"hasValue\""
: ""
};
}
)
);
const rows = '<tr>{cell}</tr>'.interpolate(
Array(size.rows).join(",").split(",")
.map( () => { return { cell: rowCells() }; } )
);
const header = ('<tr><td colspan="{colsize}" class="header">' +
'{rowsize} rows, {colsize} columns</td><tr>')
.interpolate({colsize: size.cols, rowsize: size.rows});
document.querySelector("#result").innerHTML =
'<table>{rows}</table>'
.interpolate( { rows: header + rows });
}
function getUniqueRandomValues(nValues, maxRandomValue) {
let existing = {};
maxRandomValue -= 1;
const randomUnique = () => {
const rndm = Math.floor(1 + Math.random() * maxRandomValue);
const exists = existing[rndm];
if ( !exists ) { existing[rndm] = 1; }
return exists ? randomUnique() : rndm;
};
return Array(nValues).join(",").split(",")
.map( () => randomUnique() ) ;
}
function interpolate(string2Interpolate, tokens) {
if (!(tokens instanceof Array) && tokens instanceof Object) {
tokens = [tokens];
} else if (!(tokens instanceof Object)) {
return string2Interpolate;
}
let replacer = function (token) {
return function (t, t1, t2) {
return token[t2] === ''
? String.fromCharCode(0)
: token[t2] || t;
};
}
let str = string2Interpolate;
return tokens.map(function (token) {
return str.replace(/(\{?)([a-z_0-9]+)(\})/gi, replacer(token));
}).join('').replace(RegExp(String.fromCharCode(0), "g"), '');
}
}());
body { font: 12px verdana, arial; }
table { margin-top: 1em; }
table td {
text-align: right;
border: 1px solid #c0c0c0;
padding: 2px;
min-width: 1.2em;
min-height: 1.2em;}
table td.header {
background-color: black;
color: white;
text-align: center;
}
td.hasValue {
background-color: green;
color: white;
}
td.hasValue:before {
content: "1";
}
<div id="buttons">
<button id="button1" data-table="6x6">
6x6 Table
</button>
<button id="button2" data-table="8x8">
8x8 Table
</button>
<button id="button3" data-table="16x16">
16x16 Table
</button>
</div>
<div id="result"></div>

Categories

Resources