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?
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?
var newContent = $('<your html="here"/>');
var insertLocation = $('#div1');
insertLocation.append(newContent);
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');
There are many different ways you could go with this. One way is to do something like this:
// $(document).ready() makes sure that nothing happens until the page
// is fully loaded. It's important because the div may not have loaded
// yet if you put code outside of this
$(document).ready( function() {
$("#div1").append(
"<table><tr><td>My column 1, row 1</td>" +
"<td>My column 2, row 2</td></tr>" +
"<tr><td>My column 1, row 2</td>" +
"<td>My column 2, row 2</td></tr></table>");
});
This will put the full table into your div, parsed as HTML. Another way, if you want to add each row separately, would be:
$(document).ready(function() {
$("#div1").append("<table id=\"my_table1\"></table>");
$("#my_table1").append("<tr><td>Row 1</td></tr>");
... insert more rows here ...
$("#my_table1").append("<tr><td>Row ...</td></tr>");
});
It's important to understand that .append()
will put the HTML or text you enter inside of whatever element you selected using the dollar-sign selector ($("selector text")
)