J. Doe J. Doe - 2 months ago 8
HTML Question

How do I add 'x' number of <td> elements into a <tr> element in a for loop? [jQuery]

I am trying to make a square table dynamically through jQuery

My code so far is

$(document).ready(function() {
$('body').append('<table></table>');
initial();
});

var input = 16

function initial () {
for (i = 0; i < input; i++) {
$('table').append('<tr></tr>');
$('tr').append('<td></td>');
}
}


What I am trying to do is if I add 16 table row elements, then 16 table data elements will be added to each one, effectively creating a 16x16 grid

My current code only creates half of the table
I have to do this through jQuery

Sorry if it's simple, but I'm a bit daft

Thanks

Answer

You have to make two loops one after another:

$(document).ready(function() {
  $('body').append('<table></table>');
  initial();
});

var input = 16

function initial () {
  for (i = 0; i < input; i++) {
    $('table').append('<tr></tr>');
  }
  for (j = 0; j < input; j++) {
    $('tr').append('<td>content</td>');    
  }
}

Btw its wrong way to create table, because you every time referring to DOM, which is expensive. You should first create string with table, then append it once to DOM:

var input = 16
function initial () {
  var output = "<table>"
  for (i = 0; i < input; i++) {
    output += "<tr>";
    for (j = 0; j < input; j++) {
      output += "<td>content</td>";
    }
    output += "</tr>";
  }
  output += "</table>"
  $('body').append(output);
}