Home > Misc > DataTable – Destory() method not removing all the rows

DataTable – Destory() method not removing all the rows

In one of my Dynamics portal’s requirements, I had to use Data Tables table control to bind the search results.

DataTable

I used below snippet to bind the results.

var table = $(‘#customGrid‘).DataTable({
data: rows,
destroy: true,
columns: columns,
oLanguage: {
sLengthMenu: ‘Show _MENU_ items’,
sInfo: ” <b>Showing _START_ – _END_ of _TOTAL_ items</b>”,
sInfoEmpty: ‘ <b>Showing 0 – 0 of 0 items</b>’,
sEmptyTable: “No data to display”
},
‘columnDefs’: [
]
});

In the above snippet

  • #customGrid – Is ID of a HTML <Table> object which we use for DataTable.
    • <table id=”customGrid” class=”display”></table>
  • rows – JSon collection

Problem statement:

I am using ‘DataTable’ in one of my custom HTML Search pages

  • I was binding the Search results to the DataTable up on Search button click and have to clear the previous results when no match results found.
  • I was calling destroy() function to clear off the rows from previous Search.

if ($.fn.DataTable.isDataTable(“#customGrid”)) {
$(“#customGrid”).DataTable().destroy();
}

  • However, destroy() its not removing all the rows.

Reason and Fix:

  • destroy() remove all defined events and properties of DataTable object.
  • Its not clearing the <table> object rows (This may have fixed or changed in latest versions)
  •  So, to clear the rows, you must call empty() function of <table> object.
  • Below is the final code

if ($.fn.DataTable.isDataTable(“#customGrid”)) {
     // Destroy ‘DataTable’ object
$(“#customGrid”).DataTable().destroy();
    // Remove the <table> rows
    $(“#customGrid”).empty();
}

🙂

Advertisement
Categories: Misc Tags: ,
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: