JQuery1.8 Datatables saving state on click of a button
Asked Answered
H

1

5

I have a jsp with a table and two buttons "home" and "back" in it and have imported jquery.datatable.js in it.

On click of "home" the page should load without any pagination or filter saved. and on click of "back" the table should have all the filter and pagination saved.

I have tried setting the "bStateSave" flag true while initializing the data table. This always loads the table with the filter and pagination.

Is there any way I can load the table with saved state on click of "back" button and its original state on click of "home" button

Hayner answered 12/6, 2015 at 7:43 Comment(0)
L
4

For DataTables 1.10:

Below are API functions for DataTables 1.10 related to state saving:

state()
Get the last saved state of the table

state.clear()
Clear the saved state of the table.

state.loaded()
Get the table state that was loaded during initialisation.

state.save()
Trigger a state save.

You need to have stateSave: true initialization option to enable state saving. Then, when user clicks the "Home" button, you can call $('#example').DataTable().state.clear() to clear the saved state.

For DataTables 1.9 and earlier:

Unfortunately there is no direct API method to clear saved state.

You need to have bStateSave: true initialization option to enable state saving.

Option 1: Using document.cookie:

Below is a hack intended to clear cookie that contains state data. When user clicks the "Home" button, you need to execute the code below. IMPORTANT: Replace example with your table ID.

// Reset current state
document.cookie = name + 'SpryMedia_DataTables_' + 'example' + '=; expires=Thu, 01 Jan 1970 00:00:01 GMT;';

Option 2: Using fnStateLoadParams:

Alternatively, you may want to use fnStateLoadParams callback function to determine when to load or ignore state data. Determine on page load whether state should be loaded or ignored by assigning true or false respectively to loadStateParams variable:

$(document).ready( function() {
  $('#example').dataTable( {
    "bStateSave": true,
    "fnStateLoadParams": function (oSettings, oData) {
       // Disallow state loading by returning false  
       var loadStateParams = false;

       return loadStateParams;
    }
  });
});
Lionfish answered 12/6, 2015 at 15:49 Comment(4)
But my application uses jquery 1.8.2, I cant change the version and have to implement using thatHayner
@swathiethiraj, 1.10 is the DataTables version, not jQuery. What DataTables version you're using?Lionfish
I'm using 1.8.2 datatable versionHayner
@swathiethiraj, let me see if I can update the answer for your DataTables version.Lionfish

© 2022 - 2024 — McMap. All rights reserved.