4

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?

1 Answer 1

7

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 TRs 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/

Sign up to request clarification or add additional context in comments.

9 Comments

one liner: dt.row.add($tr).draw();
@Daniel: I am looking for a way that allows jQuery additions to be made independent of DataTables, to allow for same table to be usable with DataTables on or off. If yours had worked that would have been closer
Then you should write a function that checks if your table is wrapped by an element with dataTables_wrapper style class, and if so call the datatables refresh code, otherwise call the plain table refresh code (if you got some)
@Daniel: Good idea. At least then it will only have one code path. I will probably wrap it as a $(element).appendRow() jQuery extension and post it here.
The dataTables_wrapper class is being added by the datatables api... you just need to check for its presence...
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.