Which is the best way to create dynamic tables from scratch in jQuery and then populate them with data.
EDIT :
Assume data comes from a script service and I need to create a table dynamically and populate them with the incoming values
Which is the best way to create dynamic tables from scratch in jQuery and then populate them with data.
EDIT :
Assume data comes from a script service and I need to create a table dynamically and populate them with the incoming values
DataTables is a feature-rich jQuery Table plugin. Without knowing the functionality required by your application, it's hard to make perfect recommendations, though.
There are a few ways to accomplish the actual creation of the table without plugins. For example:
$('body').append('<table id="myTable"></table>');
You can then use .append
to append table headers and rows by calling the table's id. Using .html
will allow you to populate the table.
Writing in a closure to avoid global variables. You can move the code out of the closure (first and last lines) when you put it into your app.
Assigning the table to a variable helps since you've got a resource to manipulate later, instead of requerying which can be taxing. myTable
is a jQuery object, hence the example html()
call, that'll add <thead>
and <tbody>
tags to your table element.
Also note that when you manipulate any element's inner contents, it's always best to wrap all your content inside as few elements as possible, since it will increase manipulation speed.
(function() {
var myTable = $('<table></table>');
$('body').append(myTable);
myTable.html('<thead></thead><tbody></tbody>');
})();
You can use jTemplates or DOM creation plugin to write easy to read code.
I'm doing something like this, to avoid having to write all the html in Javascript strings:
An HTML template as part of the document:
<table id="template">
<thead>...</thead>
<tbody>
<tr class="template">
<td class="var1"></td>
<td class="var2"></td>
</tr>
</tbody>
</table>
And some Javascript:
var trTemplate = $("#template").find("tr.template");
var row, value, body = trTemplate.parent();
for (var i=0; i< data.length; i++) {
value = data[i];
row = trTemplate.clone();
row.find(".var1").text(value.x);
row.find(".var2").text(value.y);
body.append(row);
}
If it is a big table, performance is significantly better if you build the table before inserting it into the document, just add a second clone()
for the whole table.
You can hide the template with a CSS rule, or merely overwrite it with the clone.