I thought this one would be simple, but I can't find a reference that is not about ajax loaded data or data supplied in an array. I am using DataTables on an existing HTML table with this basic code:
$('table.wizard').dataTable({
lengthChange: false,
iDisplayLength: 100,
order: [[9, 'desc']]
});
I am adding rows to a table, dynamically, as data records are found like this:
var $body = $('table.wizard tbody');
$tr = $("<tr>").appendTo($body).attr({ 'id': 'sku' + item.MerchantSKU, 'data-sku': item.MerchantSKU });
// then append the individual tds
[snip]
// Now how to tell the datatables it has changed?
How do I inform DataTables about the new rows?
After a few experiments, as the documentation and examples are not very clear for DOM tables, it turns out you can use the same row.add()
method for adding HTML TR
s as you would for objects and arrays. You then call the draw()
method to make the changes visible:
e.g.
dt.row.add($tr);
dt.draw();
JSFiddle: http://jsfiddle.net/TrueBlueAussie/HEDvf/2205/
Unfortunately it does allow you to refresh additions made with jQuery (which is ideally what I really wanted to allow for transparent use of DataTables) :(
Final solution (for now):
I added a custom appendRow()
jQuery extension, that checks if the table is a DataTable and redirects the append via the DataTables api if needed:
// Assume we only append to one table at a time (otherwise rows need to be cloned)
$.fn.appendRow = function ($rows) {
if ($(this).parent().hasClass("dataTables_wrapper")) {
var dt = $(this).dataTable().api();
$rows.each(function () {
dt.row.add(this);
});
dt.draw();
} else {
$(this).append($rows);
}
}
JSFiddle: http://jsfiddle.net/TrueBlueAussie/HEDvf/2212/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With