'How to clear datatable filters?
Im using custom filtering for my datatable using the method:
$.fn.dataTableExt.afnFiltering.push("custom filter function");
This function adds a filter to my datatable.
The problem is that when I use ajax to create an other datatable object, this filter persists and is applied to this other table that should have nothing to do with this filter. How do I clear the filter or bind it to the first datatable only?
Solution 1:[1]
if you make a push on $.fn.dataTableExt.afnFiltering, it means it's an array. So when you receive your data, you can remove the filter reference in this array by using :
delete $.fn.dataTableExt.afnFiltering[index or key];
this method will set the element to undefined
or by using the splice method in javascript.
$.fn.dataTableExt.afnFiltering.splice(index,1);
this method will remove the element from the array. so
var index = $.fn.dataTableExt.afnFiltering.indexOf("custom filter function");
$.fn.dataTableExt.afnFiltering.splice(index,1);
should resolve your problem (you can have precision here Javascript - remove an array item by value as indexOf is not supported by IE<9)
Solution 2:[2]
If you are going to use the 1.10+ version of the datatable in the future, the use of the search plug-in document is shown below:
To reset the filter for version 1.10+, simply add any of the following;
$.fn.dataTable.ext.search = [];$.fn.dataTable.ext.search.pop();
after this blocks you can add;
table.draw();
Solution 3:[3]
$.fn.dataTableExt.afnFiltering.pop();
credit to @DrewT
Solution 4:[4]
As mentioned from @kthorngren, there is no build in way of tracking, if or how much custom searches are active.
If you are sure, that there is only one custom search is active a$.fn.dataTableExt.afnFiltering.pop();
will work - there is big BUT:
$.fn.dataTable.ext.search is an array which contains the search settings for custom search and for searchPanes.
An erasing of this array with $.fn.dataTable.ext.search = []; or two pop()'s, allthough there is only one custom search is active --> will brake searchPanes.
e.g. if you have three panes active, this would mean:
$.fn.dataTable.ext.search[0] -> SearchPane Col1
$.fn.dataTable.ext.search[1] -> SearchPane Col2
$.fn.dataTable.ext.search[2] -> SearchPane Col3
$.fn.dataTable.ext.search[3] -> Custom Search -> safe to delete
$.fn.dataTable.ext.search[4] -> Custom Search -> safe to delete
Following code does the job in my case:
let lenOfSearchPanes = dt.settings()[0]._searchPanes.c.columns.length;
let lenOfSearchArr = $.fn.dataTable.ext.search.length;
let diff = lenOfSearchArr - lenOfSearchPanes
if (diff > 0) {
$.fn.dataTable.ext.search = $.fn.dataTable.ext.search.slice(0, -diff);
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Community |
| Solution 2 | omernaci |
| Solution 3 | |
| Solution 4 |
