Reputation: 461
[User may enter number of rows and columns, then chess board appears after clicking enter button.][The problem is I cannot fill the table cells with random numbers using Fill button]
So far the code of JavaScript is
var a, b, tableElem, rowElem, colElem;
function createTable() {
a = document.getElementById('row').value;
b = document.getElementById('column').value;
if (a == "" || b == "") {
alert("Enter a number");
} else {
tableElem = document.createElement('table');
for (var i = 0; i < a; i++) {
rowElem = document.createElement('tr');
for (var j = 0; j < b; j++) {
colElem = document.createElement('td');
rowElem.appendChild(colElem);
if (i % 2 == j % 2) {
colElem.className = "white";
} else {
colElem.className = "black";
}
}
tableElem.appendChild(rowElem);
}
document.body.appendChild(tableElem);
}
}
and Html is
<div class="form-inline">
<div class="form-group">
<input type="text" class="form-control" id="row" placeholder="Row">
</div>
<div class="form-group">
<input type="text" class="form-control" id="column" placeholder="Column">
</div>
<button type="button" class="btn btn-primary" onclick="createTable()">
Enter
</button>
<button onclick="fillTable()" id="btn" type="button" class="btn btn-info">
Fill
I used jQuery
$(document).ready(function () {
$('#btn').click(function () {
$(colElem).append(1);
});
});
but with this code only bottom right corner is filled. Please can you give info how to fill all cells of the table with random number via Fill
button
Upvotes: 2
Views: 834
Reputation: 621
$(colElem) selector pointing to the last cell of the table... you need to select each and every cell and assign the random number... look into the below code (it will add random number between 0 to 99) to solve the issue... remove onclick="fillTable()"
from the button..
$('#btn').click(function () {
$(tableElem).find("td").each(function(){
$(this).html(Math.floor(Math.random() * 100));
});
});
Upvotes: 1