Resetting or clearing all search plugins
Resetting or clearing all search plugins
Hi all.
I am trying to create a set of options as filters for a DataTable. This is all dynamically generated, so I can't hard-code in things such as the column number to search on—in case that matters at all.
Basically I will have groups (one for each column of the DataTable) of checkboxes which the user can select as a "filter". I have a search plug-in working that allows for an "OR" search since they may select multiple strings to search on.
I have it working, but somewhere along the way I lose the ability to clear, or reset the search—so after "filters" have been checked ( search has been performed via table.draw() ) and then the user un-checks all of them (clearing all of the filters) there seems to still be a search which is technically empty and telling Datatables to search without any results so the table is blank.
I hope this makes sense. Here is my code...
var table = $('#submission-list').DataTable();
var search_array = [];
$('.zfilter-checkbox').each(function(){
$(this).change(function(){
var val = $.fn.dataTable.util.escapeRegex(
$(this).val()
);
if( this.checked ){
search_array.push( val );
}else{
if( search_array.includes( val ) ){
search_array.splice( val, 1 );
}
}
$.fn.dataTable.ext.search.push(
function( settings, data, index, rowData, counter ){
search_column = data[5].split(", ");
console.log( 'search column:' );
console.log( search_column );
console.log( 'search array:' );
console.log( search_array );
for( c=0; c < search_column.length; c++ ){
if( search_array.includes( search_column[c] ) ){
console.log('returned true');
return true;
}
}
console.log('returned false');
return false;
}
);
table.draw();
$.fn.dataTable.ext.search.pop();
});
});
This question has an accepted answers - jump to answer
Answers
Here are some screenshots that hopefully help explain what I'm trying to do and the issue I'm having.
Thanks for any and ALL help!
Jon
I built a test case with your code:
http://live.datatables.net/vidolumo/1/edit
There were two issues. The way you were removing elements from the search_array wasn't correct and many times removed the wrong item. The first parameter of the slice() function is an index not a string value. You need to get the index of the checkbox value then use slice() to remove the element using the index.
The second is when the array is empty
[]
then just returntrue
for all rows.The example has both these updates and seems to work.
Kevin
Thank you so much, Kevin.
I just figured out the indexOf issue when removing elements from the array—complete face-palm!!!
I was also so close to returning true if the array was empty!
Thanks again for the help. You are awesome.
-Jon