Replace the table body using DataTables
I'm new to using DataTables and I'v been struggling to change the body of my DataTable.
I have been looking at the API and searching the forum but I could not find anything.
The API has a function called body()
which is for getting table body. It would have been fantastic if there were a function for setting it.
Imagine I am getting a whole new table body through AJAX and I want to remove the old body and put it instead.
I used to do it by the jQuery function html()
but looks like things are different here.
Solution 1:
If you need to replace all rows, I would recommend using combination of clear()
and rows.add()
.
For example:
var table = $('#example').DataTable();
table.clear();
table.rows.add( [
{
"name": "Tiger Nixon",
"position": "System Architect",
"salary": "$3,120",
"start_date": "2011/04/25",
"office": "Edinburgh",
"extn": "5421"
}, {
"name": "Garrett Winters",
"position": "Director",
"salary": "$5,300",
"start_date": "2011/07/25",
"office": "Edinburgh",
"extn": "8422"
}
] );
Otherwise, if you want to replace table with HTML content you need to destroy the table with destroy()
, replace tbody
and then re-initialize the table again with DataTable()
.
For example:
var table = $('#example').DataTable();
table.destroy();
$('#example').html('<thead><tr><th></th></tr></thead><tbody></tbody>');
table = $('#example').DataTable();