jQuery DataTables - Replace/Update row using jQuery object. Or fnUpdate

Joel picture Joel · Aug 2, 2015 · Viewed 10.5k times · Source

I'm successfully able to add a row to the datatable using the following code:

works:

var serversTable = $('#datatable-table').dataTable().api();

var serverRowTemplate = Handlebars.compile($('#serverRowTemplate').html());

var $row = $(serverRowTemplate(data.results[r]));

serversTable.row.add($row).draw(false);

But when I try to update(replace) a row using a similar method, I have no luck. I've also tried using fnUpdate, but I can't seem to figure out the correct way to basically replace/update an existing row via a jQuery object. Here is the code that fails to update the table:

doesn't work:

var serversTable = $('#datatable-table').dataTable().api();

var oldRow = $('#dashboardTemplateContainer tr[data-tag="'+ data.results[r].tag + '"]'); // select the row i'm looking for

var serverRowTemplate = Handlebars.compile($('#serverRowTemplate').html()); //compiles the handlebars template. i need this template as i have a lot of conditionals etc. 

var $row = $(serverRowTemplate(data.results[r])); // turning the template into a jQuery object worked for the row.add() function in the above example.

serversTable.rows(oldRow).data($row).draw(false); // replace the old row with the new row. doesn't work.

Any suggestions?

Answer

Gyrocode.com picture Gyrocode.com · Aug 3, 2015

API method rows().data() can only be used to retrieve the data. Use row().data() instead to set data for a row.

However you won't be able to use jQuery object for <TR> node to update the row's data. Probably your best bet in this case would be to remove the row with row().remove() and re-add it if all you have is <TR> node.