I have a HTML table that I fill with data from an AJAX jQuery call.This table uses the jQuery plugin - datatables for paging, sorting and so on.
The jQuery call gets called from a dropdownlist change event
$("#Dropdownlist").on("change", function () {
$.ajax({
type: "POST",
url: "@Url.Action("Action", "Controller")",
//contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
$.each(data, function (key, item) {
$("tbody").append("<tr><td>appending data here</td></tr>");
});
$('#table').dataTable().fnDestroy();
$('#table').dataTable({
"aoColumns": [
{ "bSortable": false },
null, null, null, null, null
]
});
}
})
});
This jQuery has been edited to shorten it. This jQuery works great, it gets the data and add them in the new table rows while also updating the datatable plugin to make it work with the new data.
The issue is that the old data still remains, I've been trying to clean it up with various things like
$("#tbodyID tr").detach();
$("#tbodyID tr").remove();
$("#tbodyID").empty();
$("#tbodyID").html("");
$("tbody").empty();
$("tbody").html("");
$('#table').dataTable().fnDraw(false)
I put these before the AJAX call. But none works, the old data still remains and every time I call the AJAX call, it keeps refilling it with new data while the old still remains.
Is there a way to clear the tbody with either jQuery or a inbuilt datatables function?
you can use DataTables function fnClearTable and fnAddData like this
You can use the
clear()
function to remove all rows of data from the table as follows:I think what you're looking for is this piece of code:
Source: http://www.datatables.net/forums/discussion/comment/15862
Answer updated in order to target the dataTables 1.10.x API. The original answer below using
fnMethods
were targeting 1.9.x but is still applicable for any 1.9.x - 1.10.xdataTable()
.When a dataTable is instantiated with
DataTable()
which returns an API instance :As the original answer an example of emptying
<tbody>
entirely and inserting a new row :Notice
draw()
. When a table is manipulated through the API it is necessary to calldraw()
to update the display in order to reflect those changes.demo -> http://jsfiddle.net/9kLmb9fu/
You should use
Here is an example from the jsfiddle below, deleting all content from
<tbody>
(on a paginated table!) and insert a new row :see fiddle -> http://jsfiddle.net/yt57V/