Table should change the number of rows/columns? - javascript

Please see the below code, the table should change the number of rows based on input selected in the selected id option below, but only the first value of select id is read, and the number of rows are not changing based on the selection, can you please point out the mistake in my code ?
http://jsfiddle.net/uTY6n/14/
HTML:
<div id="scrollingDiv">
<select id="read">
<option value="1">1</option>
<option value="2">2</option></select>
<table id="contentTable" border="1">
<!-- Fill table programmatically -->
</table>
</div>
JAVASCRIPT:
function buildTable()
{
var myTable =document.getElementById("contentTable");
var j=document.getElementById("read").value;
var rows = [];
var cells = [];
for( var i = 0; i < j; i++ )
{
rows[i] = myTable.insertRow(i);
if(i%3==2)rows[i].addClass("everyrow");
cells[i] = [];
for( var x = 0; x < 3 ; x++ )
{
cells[i][x] =document.createElement((x==0)?"th":"td");
cells[i][x].innerHTML = (x==0)?"<input>":"<input>";
rows[rows.length - 1].appendChild(cells[i][x]);
}
}
}
buildTable();
CSS:
#scrollingDiv
{
border: 1px groove black;
height: 350px;
width: 350px;
background: #ffffff;
overflow: auto;
}
#contentTable
{
height: 350px;
width: 350px;
}
.every3rdrow{
border-bottom:3px solid black;
}

See this demo.
First, you need to attach an event listener to the <select>:
document.getElemenyById('read').addEventListener('change', buildTable);
Then, you need to make sure the table is emptied before it's rebuilt every time buildTable() is called:
function buildTable() {
var myTable =document.getElementById("contentTable");
var j=document.getElementById("read").value;
var rows = [];
var cells = [];
while (myTable.hasChildNodes()) {
myTable.removeChild(myTable.lastChild);
}
...
}
Hope this helps!

try
function buildTable() {
var myTable =document.getElementById("contentTable");
myTable.innerHTML = "";
var j=document.getElementById("read").value;
var rows = [];
var cells = [];
var myHtml = "";
for( var i = 0; i < j; i++ ) {
myHtml += "<tr>";
for( var x = 0; x < 3 ; x++ ){
myHtml += "<td></td>"
}
myHtml += "</tr>";
}
myTable.innerHTML = myHtml;
}
thats the general idea, also be sure to call this onChange of your select.

Related

javascript dynamic table filling

I have multiple arrays lets say:
var animals = ["cow","horse","rabbit","elephant","donkey","monkey","zebra"];
var food = ["apple","banana","pear","melon","grape","peach","pineapple"];
I want to put this in 4-column table dynamically. if click on animals picture the animals array would fill the table, if food, then food array would fill the table.
So, lets say I have
<table class="myTable"></table>
Then need javascript
import $ from "https://cdn.skypack.dev/jquery#3.6.1";
var animals = ["cow","horse","rabbit","elephant","donkey","monkey","zebra"];
var food = ["apple","banana","pear","melon","grape","peach","pineapple"];
var $table = $('.myTable');
for (var i = 0; i < food.length; i++){
var $aSingleContent = '<tr><td>'+food[i]+'</td></tr>';
$table.append($aSingleContent);
}
This would display all food items in 1 column. Now I need to divide this by 4 - because 4 columns in a row
because of <tr> in line var $aSingleContent = '<tr><td>'+food[i]+'</td></tr>'; makes your javascript create a new row for every element in array. we need to keep count the amount of data that had filled a row. if a row has 4 columns columnCount === 4, then we create a new row.
const food = ["apple","banana","pear","melon","grape","peach","pineapple"];
const $table = $('.myTable');
let $aSingleContent = "<tr>", columnCount = 0;
for (var i = 0; i < food.length; i++){
if(columnCount === 4) {
columnCount = 0;
$aSingleContent += '</tr><tr>';
}
$aSingleContent += '<td>'+food[i]+'</td>';
columnCount++;
}
$aSingleContent += "</tr>"
$table.append($aSingleContent);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="myTable" border></table>
You can try this:
window.onload = function() {
var animals = ["cow","horse","rabbit","elephant","donkey","monkey","zebra"];
var food = ["apple","banana","pear","melon","grape","peach","pineapple"];
var table = document.getElementById("table");
var i = 0, r = 0;
while(i < animals.length) {
var row = table.insertRow(r);
for (var c = 0; c < 4; c++) {
var cell = row.insertCell(c);
cell.appendChild(document.createTextNode(animals[i] ? animals[i] : ''));
i++;
}
r++;
}
document.body.appendChild(table);
}
table, th, td {
border: 1px solid black;
border-collapse: collapse;
}
th, td {
padding: 15px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="table" cellpadding="1" cellspacing="1">
</table>
Hope this help!
If you have food array more than you provide you can use this one.
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.6.1.slim.min.js" integrity="sha256-w8CvhFs7iHNVUtnSP0YKEg00p9Ih13rlL9zGqvLdePA=" crossorigin="anonymous"></script>
</head>
<body>
<table class="myTable" border="1">
</table>
<script>
var animals = ["cow","horse","rabbit","elephant","donkey","monkey","zebra"];
var food = ["apple","banana","pear","melon","grape","peach","pineapple", "a","b","c","d"];
var $table = $('.myTable');
var $aSingleContent = '';
var to = 0;
var from = 3;
for (var i = 0; i < food.length; i++){
if (i==to)
{ $aSingleContent += '<tr>'; }
$aSingleContent += '<td>'+food[i]+'</td>';
if (i==from)
{
$aSingleContent += '</tr>';
to = to + 4;
from = from + 4;
}
}
$table.append($aSingleContent);
</script>
</body>
</html>

Javascript function does not run after a function that I created

I am trying to develop a pretty simple and straight forward website. I have a table and a user can fill information in the input="text" fields. I add rows with the plus button that triggers the insertRow() function and remove rows with removeRow() function dynamically. The wipe button removes every text from input="text" fields. When I click the proceed button, the function proceed() is triggered which rebuilds the above table in a new one below. After the rebuild, I add the text from the fields and then, run the removeButtons() function to remove all the buttons from the right side of the tables.
The problem is that I run the removeButtons() inside the proceed() function but the removeButtons() does not get executed. I can not seem to find what is wrong even though I spend quite some time trying to solve the problem, that is why I am requesting help from people with much more experience than me. I know probably the problem is in the proceed() function but I tried several things from which none solved my problem.
My code:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style>
.btndiv {
position: relative;
top: -20px;
}
.btn {
position: absolute;
right: -30px;
width: 20px;
height: 20px;
background-image: url(minus.jpg);
cursor: pointer;
}
.btnPlus {
position: absolute;
right: -60px;
width: 20px;
height: 20px;
background-image: url(plus.jpg);
cursor: pointer;
}
.hideP {
display: none;
}
table,
td,
th {
border: 1px solid #ddd;
}
table {
border-collapse: collapse;
}
</style>
<script>
function insertRow() {
//>>> Inserting a row and a div that holds the buttons on every last cell in each row
var table = document.getElementById("myTable");
var count = document.getElementById("myTable").rows.length;
var row = table.insertRow(count);
var cell = 0;
while (cell <= 6) {
var cl = row.insertCell(cell);
cl.innerHTML = "<input type='text' />";
if (cell == 6) {
cl.innerHTML = "<input type='text' /><div class='btndiv'><div class='btn' onclick='deleteRow(this.id)'></div><div class='btnPlus' name='plus' onclick='insertRow()'></div></div>";
}
cell++;
}
hidePlus();
resetIds();
}
function deleteRow(theId) {
//>>> Deleting a row
var count = document.getElementById("myTable").rows.length;
if (count == 3) {
alert("The table must have at least one row!");
} else {
theId++;
theId++;
document.getElementById("myTable").deleteRow(theId);
hidePlusDelete();
resetIds();
}
}
function resetIds() {
//>>> Resetting the ids of my buttons dynamically (when inserting or removing row)
var count = document.getElementById("myTable").rows.length;
var x = document.getElementsByClassName("btn");
var y = 0;
var temp;
while (y <= count) {
temp = x[y];
temp.setAttribute("id", y);
y++;
}
}
function hidePlus() {
//>>> Hiding all plus buttons in every row except the last one on the right side of the minus button
var count = document.getElementById("myTable").rows.length;
if (count > 3) {
var x = document.getElementsByClassName("btnPlus");
var xlength = x.length;
var xlengthnew = xlength - 1;
var y = 0;
var temp;
while (y < xlengthnew) {
temp = x[y];
temp.setAttribute("class", "hideP");
y++;
}
}
}
function hidePlusDelete() {
var count = document.getElementById("myTable").rows.length;
if (count >= 3) {
var x = document.getElementsByClassName("hideP");
var xlength = x.length;
var xlengthnew = xlength - 1;
var y = 0;
var temp;
if (y === xlengthnew && count < 3) {
temp = x[y];
temp.setAttribute("class", "btnPlus");
}
}
}
function clearTable() {
//>>> Clear all input="text" fields
var inp = document.getElementsByTagName('input');
for (var i in inp) {
if (inp[i].type == "text") {
inp[i].value = "";
}
}
}
function proceed() {
//>>> Get text from text boxes and store them in the text variable
//>>> Counter variable to get the number of input="text" fields
var text = "";
var count = 0;
var inp = document.getElementsByTagName("input");
for (var i in inp) {
if (inp[i].type == "text") {
text += inp[i].value;
text += ";";
count++;
}
}
//>>> Store the HTML code from myTable in data variable
//>>> Put the HTML code in newTable
var data = document.getElementById("myTable").innerHTML;
document.getElementById("newTable").innerHTML = data;
//>>> Splitting my text in parts
//>>> Put the text in the input="text" of newTable
var temp = 0;
var counter = 0;
var tempor;
var temporary;
var values = text.split(";");
var p2inp = document.getElementsByTagName("input");
for (var c in p2inp) {
if (p2inp[c].type == "text") {
temp = counter + count + 2;
tempor = p2inp[temp];
temporary = values[counter]
tempor.value = temporary;
//inp[temp].setAttribute("readonly", "readonly");
//inp[temp].setAttribute("disabled", "disabled");
counter++;
}
}
//>>> Hiding buttons from the tables
//>>> The buttons are divs modified to look like buttons with css
removeButtons();
}
function removeButtons() {
//>>> Adding the css class hideP (display="none")
alert("in remove buttons");
var divcount = document.getElementsByClassName("btndiv").length;
alert(divcount);
var divcounter = 0;
var divtemp = 0;
var divinp = document.getElementsByClassName("btndiv");
while (divcounter <= divcount) {
divtemp = divinp[divcounter];
divtemp.setAttribute("class", "hideP");
divcounter++;
}
}
window.onload = insertRow;
</script>
</head>
<body>
<table id="myTable" style="width: 50%">
<col>
<colgroup span="2"></colgroup>
<colgroup span="2"></colgroup>
<tr>
<th colspan="1" rowspan="2">Name, strength and form of medicine</th>
<th colspan="1" rowspan="2">What it's for</th>
<th colspan="4" scope="colgroup">How much to take, when</th>
<th colspan="1" rowspan="2">Extra instructions</th>
</tr>
<tr>
<th scope="col">Breakfast</th>
<th scope="col">Midday meal</th>
<th scope="col">Evening meal</th>
<th scope="col">Bed Time</th>
</tr>
</table>
<br/>
<input type="image" src="whipe.png" onclick="clearTable()" width="50px" height="50px" />
<input type="image" src="go.png" onclick="proceed()" width="50px" height="50px" />
<br/>
<br/>
<br/>
<table id="newTable" style="width: 50%"></table>
</body>
</html>
Your problem (maybe) is this loop, if you comment it out, the desired function will run, so start search for an error here, or from the used variables in your loop:
for (var c in p2inp) {
if (p2inp[c].type == "text") {
temp = counter + count + 2;
tempor = p2inp[temp];
temporary = values[counter]
tempor.value = temporary;
//inp[temp].setAttribute("readonly", "readonly");
//inp[temp].setAttribute("disabled", "disabled");
counter++;
}
}
And as others said, always check for errors in the console.
Also I recommend to try start to debug your javascript.

selecting multiple table row using shift key and control key is not working

hi i have a editable table which is created by using java script.here i use some code for selection process .i want select table row using control key and shift key . i get the code from
[1]: http://jsfiddle.net/g8Rpe/ here. this example shown for html table .but my table is daynamic one
the code is here:
/******for table**************/
$(function () {
function tableCreate() {
var body = document.body,
tbl = document.createElement('table');
tbl.style.width = '100%';
tbl.style.borderCollapse = 'collapse';
for (var i = 0; i < 30; i++) {
var tr = tbl.insertRow();
tr.setAttribute("data-id", i, 0);
for (var j = 0; j < 3; j++) {
var td = tr.insertCell();
td.appendChild(document.createTextNode(''));
}
}
$("body").append(tbl);
$("td").addClass("mainheading4")
$("tr").on("onmousedown=RowClick(this,false)")
}
tableCreate();
//******************for editable table*************************//
$('td').click(function () {
$('td').attr('contenteditable', 'true');
})
//************for multiple selection*****************//
var lastSelectedRow;
var trs = document.getElementById('table').tBodies[0].getElementsByTagName('tr');
// disable text selection
document.onselectstart = function () {
return false;
}
function RowClick(currenttr, lock) {
if (window.event.ctrlKey) {
toggleRow(currenttr);
}
if (window.event.button === 0) {
if (!window.event.ctrlKey && !window.event.shiftKey) {
clearAll();
toggleRow(currenttr);
}
if (window.event.shiftKey) {
selectRowsBetweenIndexes([lastSelectedRow.rowIndex, currenttr.rowIndex])
}
}
}
function toggleRow(row) {
row.className = row.className == 'selected' ? '' : 'selected';
lastSelectedRow = row;
}
function selectRowsBetweenIndexes(indexes) {
indexes.sort(function (a, b) {
return a - b;
});
for (var i = indexes[0]; i <= indexes[1]; i++) {
trs[i - 1].className = 'selected';
}
}
function clearAll() {
for (var i = 0; i < trs.length; i++) {
trs[i].className = '';
}
}
});
body{font-size:62.5%;}
td { padding: 0.2em 0.4em; }
.selected { background: lightBlue }
.mainheading4{
border: 1px solid;
border-color: lightgray;
width:33.3%;
height:17px;
font-size:15px;
padding-left: -5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
i use
$("tr").on("mousedown=RowClick(this,false)") <
for getting mouse event.
but its not taken.
There are couple of wrong doings.
1) Assign id to table without which you will not get table rows as in below line
var trs = document.getElementById('table').tBodies[0].getElementsByTagName('tr');
E.g. In your tableCreate method add below lines of code.
var body = document.body,
tbl = document.createElement('table'),
tableId = document.createAttribute('id');
tableId.value = "table";
tbl.setAttributeNode(tableId);
2) Second register mouse down event like suggested by feela,
$(document).on('click', 'tr', function () {
RowClick(this, false);
});
Hope it will resolve your issue.
This is not a valid syntax for on. See: http://api.jquery.com/on/
What you probably meant was:
$("tr").on("mousedown", function(event) {
RowClick(event.target, false);
});

How to create board NxN using JavaScript and jQuery

I am trying to create board game (like chess board game) with JavaScript.
When I tried to do it this is what happened:
The <tr> got closed immediately with </tr>, same thing with <table> </table>
I tried to replace the append() method with appendTo() or add() but it didn't help
This is my JavaScript code:
var boardSize = 5;
$(function() { //on load
printBoard(boardSize);
});
function printBoard(i_BoardSize) {
var maxRow = parseInt(i_BoardSize);
var maxCol = parseInt(i_BoardSize);
var num = 1;
$("#board").append("<table oncontextmenu=\"return false\">");
for(var row = maxRow - 1; row >= 0 ; row--) {
$("#board").append("<tr>");
for(var col = 0; col < maxCol ; col++) {
$("#board").append("<td>" + num + "</td>");
num++;
}
$("#board").append("</tr>");
}
$("#board").append("</table>");
}
CSS:
td {
width: 32px;
height: 32px;
cursor: pointer;
text-align: center;
border: 2px solid blue;
}
.redborder {
background-color: red;
color: white;
}
.blueborder {
background-color: blue;
color: white;
}
HTML:
<!DOCTYPE html>
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel='stylesheet' type='text/css' href='css/board.css' />
<script type="text/javascript" src="jquery-2.1.1.min.js"></script>
<script type="text/javascript" src="Scripts/board.js"></script>
</head>
<body>
<p> <center><h3><font size="20" color="black"> Board Game</font></h3></center></p>
<div>
<div id="board">
<div class="cell">
</div>
</div>
</div>
</body>
</html>
This happens because jQuery append() method not supporting only closing tags and trying to close tags if they wasn't closed in provided param. To solve this you need to assign your append() result to some variable, for example:
var myTable = $("<table oncontextmenu=\"return false\"></table>").appendTo("#board");
and then append your rows to this var:
var myRow = $("<tr></tr>").appendTo( myTable );
Same with columns:
myRow.append("<td>" + num + "</td>");
By using appendTo method you will be able to get newly created elements.
So your final code should look like:
var boardSize = 5;
$(function() { //on load
printBoard(boardSize);
});
function printBoard(i_BoardSize) {
var maxRow = parseInt(i_BoardSize);
var maxCol = parseInt(i_BoardSize);
var num = 1;
var myTable = $("<table oncontextmenu=\"return false\"></table>").appendTo("#board");
for (var row = maxRow - 1; row >= 0; row--) {
var myRow = $("<tr></tr>").appendTo(myTable);
for (var col = 0; col < maxCol; col++) {
myRow.append("<td>" + num + "</td>");
num++;
}
}
}
The others have supplied you with why this is happening but I thought I might give an example of how you might make better use of css and more recent dom usage.
Fiddle: http://jsfiddle.net/np62shu6/1/
But the basic idea is to define the number of cells, then write out a series of divs that have a 20% float value. In the end you have a chess board with a cell data attribute.
HTML:
<div id="game">
</div>
CSS:
.cell{
width:20%;
float:left;
text-align:center;
}
.odd{
background:#eee;
}
JS (assumed you place this in a load handler):
var cells = 25;
var cell;
var h;
for(var i = 1; i <= cells; i ++)
{
cell = $('<div>').addClass('cell').attr('data-cell', i).text(i);
if(i % 2 == 1)
cell.addClass('odd');
$('#game').append(cell);
}
h = $('.cell:last-of-type').width();
$('.cell').css({height: h, lineHeight: h + 'px'});
As others have said, append is a sequential method, so calling it one after the other will just keep dropping things in the DOM. But you can create elements, then add things to those elements using append, then use append to add that whole group to another...
My example does not show this. My example is just an alternative to what you wrote. I would not do it the way you are doing it is all.
Another slight side note - chess boards have 64 cells (8 x 8), but I left it at 25 because your example did this.
When you append a tag with jQuery it doesn't work like appending text to a HTML string. Instead it creates the dom element. Try something like this instead, notice the absence of closing tags and td is appended directly to the latest tr:
var boardSize = 5;
$(function() { //on load
printBoard(boardSize);
});
function printBoard(i_BoardSize)
{
var maxRow = parseInt(i_BoardSize);
var maxCol = parseInt(i_BoardSize);
var num = 1;
$("#board").append("<table oncontextmenu=\"return false\">");
for(var row = maxRow - 1; row >= 0 ; row--)
{
$("#board table").append("<tr>");
for(var col = 0; col < maxCol ; col++)
{
$("#board tr:last").append("<td>" + num + "</td>");
num++;
}
}
}
The error is here:
function printBoard(i_BoardSize)
{
var maxRow = parseInt(i_BoardSize);
var maxCol = parseInt(i_BoardSize);
var num = 1;
$("#board").append("<table oncontextmenu=\"return false\">");
for(var row = maxRow - 1; row >= 0 ; row--)
{
#here
$("#board").append("<tr>");
for(var col = 0; col < maxCol ; col++)
{
#here
$("#board").append("<td>" + num + "</td>");
num++;
}
$("#board").append("</tr>");
}
$("#board").append("</table>");
}
You are appending each element to the #board instead of properly nesting them. try keeping the created elements in variables, and do nesting:
function printBoard(i_BoardSize)
{
var maxRow = parseInt(i_BoardSize);
var maxCol = parseInt(i_BoardSize);
var num = 1;
$tableelement = $("<table oncontextmenu=\"return false\"></table>");
$("#board").append($tableelement);
for(var row = maxRow - 1; row >= 0 ; row--)
{
#here
$rowelement = $("<tr></tr>");
$tableelement.append($rowelement);
for(var col = 0; col < maxCol ; col++)
{
#here
$rowelement.append("<td>" + num + "</td>");
num++;
}
}
}
Reason: certain browsers will immediately try to fix malformed HTML, and in the middle of the execution, the items are malformed while you insert it, and are wellformed after you finish. in the middle -this function's execution is not atomic- the code is malformed and the browser tries to fix it by closing the tags you add. That's why you need to add elements by nesting -opening and closing the tags for them beforehand-
$(function() { //on load
var boardSize = 5;
printBoard(boardSize);
});
function printBoard(i_BoardSize)
{
var maxRow = parseInt(i_BoardSize),
maxCol = maxRow;
var $table = $("<table oncontextmenu='return false'></table>").appendTo($("#board"));
for(var row = 1; row <= maxRow; row++)
{
var $row = $("<tr/>").appendTo($table);
for(var col = 1; col <= maxCol; col++)
{
$row.append("<td>" + (row*col) + "</td>");
}
}
}
td {
width: 32px;
height: 32px;
cursor: pointer;
text-align: center;
border: 2px solid blue;
}
.redborder {
background-color: red;
color: white;
}
.blueborder {
background-color: blue;
color: white;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p> <center><h3><font size="20" color="black"> Board Game</font></h3></center></p>
<div>
<div id="board">
<div class="cell">
</div>
</div>
</div>
Side note: You don't have to append the closing tags manually...
This is way easier and cleaner if you just learn JavaScript and work in the DOM.
function makeBoardWithoutJQuery(xs, ys) {
var table = document.createElement('table');
var tbody = document.createElement('tbody');
for (var y=0; y<ys; ++y) {
var tr = document.createElement('tr');
for (var x=0; x<xs; ++x) {
var td = document.createElement('td');
td.innerHTML = (y*xs) + x;
tr.appendChild(td);
}
tbody.appendChild(tr);
}
table.appendChild(tbody);
return table;
}

jQuery - How to print dynamically empty table

Can someone please tell me what I'm doing wrong?
I think it's something with the string adding;
I've also tried:
var column = $("<td></td>")
instead of:
var column = $("<td>")
etc
and it's always the same result on the HTML : "[object Object]"
What am I doing wrong?
$(function() {
createTable(8);
});
function createTableColumn() {
var column = $("<td>");
return column;
}
function createTableRow(gameBoardSize) {
var columns = "";
var row;
for(counter = 0; counter < gameBoardSize; counter++) {
columns = columns + createTableColumn();
}
row = $("<tr>").append(columns);
return row;
}
function createTable(gameBoardSize) {
var rows = "";
for(counter = 0; counter < gameBoardSize; counter++) {
rows += createTableRow(gameBoardSize);
}
$("#gameboard-table").append(rows);
}
You are accidentally performing a string concatenation operation with += createTableRow.... Change rows to an array and use push instead
var rows = [];
for(counter = 0; counter < gameBoardSize; counter++) {
rows.push(createTableRow(gameBoardSize));
}
+ is for concatenating strings, not jQuery objects.
Just append directly to the jQuery objects:
function createTableRow(gameBoardSize) {
var row = $("<tr>");
for(var counter = 0; counter < gameBoardSize; counter++) {
row.append(createTableColumn());
}
return row;
}
function createTable(gameBoardSize) {
for(var counter = 0; counter < gameBoardSize; counter++) {
$("#gameboard-table").append(createTableRow(gameBoardSize));
}
}
Make sure you use local variables for loop counters. Otherwise, the for loop in createTableRow updates the counter in createTable, which causes that loop to end prematurely.
$(function(){
createTable(8);
var i=0;
$('td').each(function(){
i++;
$(this).text(i);
});
});
function createTable(number){
for(var count = 0;count<number;count++){
$('#gameboard-table').append('<tr>');
$('tr').append('<td>');
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<table id="gameboard-table"></table>
just string concatenation and one append.
function createTable(rowsCount, columnsCount) {
var rows = "";
var cell = "";
var table = $("<table />")
for (var i = 0; i < columnsCount; i++) {
cell += "<td></td>";
}
for (var i = 0; i < rowsCount; i++) {
rows += "<tr>" + cell + "</tr>";
}
table.append(rows);
return table;
}

Categories