Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a new table with rows using jquery and wrap it inside div

I would like to create table inside a div element

On my .html file, I have this

<div id='div1'> </div>

On my js file, I want to place new table with rows and with data

How can I implement this?

like image 624
kratz Avatar asked Sep 12 '09 01:09

kratz


1 Answers

Assuming you have the HTML for the table, you can simply create a jQuery object out of it and append it to the DIV. If you have the data, you'll need to iterate through it and create the cells/rows from the data and add them independently.

$('<table><tr><td>.....</td></tr></table>').appendTo( '#div1' );

or

var data = [ [ 1, 2, 3 ], [ 4, 5, 6 ], [7, 8, 9 ] ];

var html = '<table><thead><tr>...</tr></thead><tbody>';
for (var i = 0, len = data.length; i < len; ++i) {
    html += '<tr>';
    for (var j = 0, rowLen = data[i].length; j < rowLen; ++j ) {
        html += '<td>' + data[i][j] + '</td>';
    }
    html += "</tr>";
}
html += '</tbody><tfoot><tr>....</tr></tfoot></table>';

$(html).appendTo('#div1');
like image 141
tvanfosson Avatar answered Oct 05 '22 22:10

tvanfosson