Datatables clear tbody

纵然是瞬间 提交于 2019-12-02 22:41:31

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.x dataTable().

When a dataTable is instantiated with DataTable() which returns an API instance :

var dataTable = $('#example').DataTable();

As the original answer an example of emptying <tbody> entirely and inserting a new row :

$("#delete").click(function() {
    dataTable.clear();
    dataTable.row.add([
        'new engine',
        'new browser',
        'new platform',
        'new version',
        'new css'
    ]).draw();
});

Notice draw(). When a table is manipulated through the API it is necessary to call draw() to update the display in order to reflect those changes.

demo -> http://jsfiddle.net/9kLmb9fu/


You should use

$('#table').dataTable().fnClearTable();

Here is an example from the jsfiddle below, deleting all content from <tbody> (on a paginated table!) and insert a new row :

$("#delete").click(function() {
    dataTable.fnClearTable();
    dataTable.fnAddData([
        'new engine',
        'new browser',
        'new platform',
        'new version',
        'new css'
    ]);
});

see fiddle -> http://jsfiddle.net/yt57V/

You can use the clear() function to remove all rows of data from the table as follows:

var table = $('#example').DataTable();
table.clear().draw();

you can use DataTables function fnClearTable and fnAddData like this

$("#Dropdownlist").on("change", function () {
    $.ajax({
            type: "POST",
            url: "@Url.Action("Action", "Controller")",
            //contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (data) {
                var oTable = $('#table').dataTable();//get the DataTable
                oTable.fnClearTable();//clear the DataTable
                $.each(data, function (key, item) {
                    oTable.fnAddData(["appending ","data","here"]);//add new row
                    //each element in the array is a td
                });
                /*no need to destroy and create new DataTable
                $('#table').dataTable().fnDestroy();
                $('#table').dataTable({
                    "aoColumns": [
                      { "bSortable": false },
                      null, null, null, null, null
                    ]
                });
                */
            }
        })
});

I think what you're looking for is this piece of code:

var oSettings = $('#table').dataTable().fnSettings();
var iTotalRecords = oSettings.fnRecordsTotal();
for (i=0;i<=iTotalRecords;i++) {
   $('#table').dataTable().fnDeleteRow(0,null,true);
}

Source: http://www.datatables.net/forums/discussion/comment/15862

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!