table.state.clear() does not clear saved state; how do I remove specified filters/sorts here?
table.state.clear() does not clear saved state; how do I remove specified filters/sorts here?
By default the DataTables on my page save their state, "stateSave": true
. But sometimes, depending on the Referrer to my page, I need to clear out their state and present the blank version. If the Referrer (document.referrer
) was a specific URL then I keep my state, otherwise I erase it.
Suppose I initially initialize my DataTables in Document-Ready as below (by default with stateSave = TRUE
), and then after performing my check, if appropriate, I need to clear out all filters/sorts and present a blank table. Otherwise the table is presented with the Saved State from before.
$('document').ready(function () {
// 1. Set up DataTables
$('#activeRequestsTable').DataTable({
"responsive": true,
"stateSave": true, // By default always save state. It will only be cleared in specific cases.
"ajax": { ... }
});
// etc.
// 2. If Some URL Referrer Condition satisfied, need to clear out and re-paint my DataTables
if (referrerCondition()) {
var table = $('#activeRequestsTable').DataTable();
// Clear state
table.state.clear();
// Redraw (or do something to lose the filters/sorts -- tried both, not working)
table.draw();
table.ajax.reload();
//...? what else?
}
The problem is the above code doesn't work. When I have referrerCondition
, do state.clear()
, and then redraw (both ways), I still see the saved filters/sorts. It didn't erase my state, or maybe it didn't redraw.
So why is this state-clearing not working?
Replies
I believe I fixed my problem. The
state.clear()
had to be paired with.destroy()
prior to re-initialization. Therefore, the code looks as follows now:$('document').ready(function () {
The above code works now. For the Referrer condition I lose my Filter/Sorts (State), otherwise I keep it. Let me know if I missed anything.
That is probably the easiest way to revert a Datatable back to the configured settings without reloading the web page.
Kevin