Skip to content Skip to sidebar Skip to footer

Generate Table Based On Number Of Rows, Columns In Jquery

How do I generate a table in jQuery based on a given number of rows and columns?

Solution 1:

You can use nested for loops, create elements and append them to one another. Here's a very simple example that demonstrates creating DOM elements, and appending them.

You'll notice that the $('<tag>') syntax will create an element, and you can use the appendTo method to, well, do exactly that. Then, you can add the resulting table to the DOM.

var rows = 5; //here's your number of rows and columnsvar cols = 5;
var table = $('<table><tbody>');
for(var r = 0; r < rows; r++)
{
    var tr = $('<tr>');
    for (var c = 0; c < cols; c++)
        $('<td>some value</td>').appendTo(tr); //fill in your cells with something meaningful here
    tr.appendTo(table);
}

table.appendTo('body'); //Add your resulting table to the DOM, I'm using the body tag for example

Post a Comment for "Generate Table Based On Number Of Rows, Columns In Jquery"