Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Search for multiple values in single column of dataTable (possibly use array?)

I have a dataTable that is populated with items that are either in draft, pending approval, approved or denied. The statuses of the items is in one particular column.

I would like to search this column for multiple types of statuses.

For example, I would like to search for pending and approved items, and then redraw the table to only show those items that are either pending or have been approved.

The kicker is that I would like to have this search string change dynamically through a checkbox.

The search works with hard coded values:

$('#theTable').DataTable().search('Pending').draw();

and even

$('#theTable').DataTable().search('Pending'|'Approved').draw();

But I would like to change the search string (the 'Pending'|'Approved' part) dynamically, based on checkboxes.

So...

if($("#Pending").is(":checked")) {
   searchString += 'Pending';
   $('#theTable').DataTable().search(searchString).draw();
}

if($("#Approved").is(":checked")) {
   searchString += 'Approved';
   $('#theTable').DataTable().search(searchString).draw();
}

But this doesn't work. I have tried concatenating, using an array, using fnFilter rather than search, but nothing seems to work.

Any ideas??

like image 951
Apolymoxic Avatar asked Jul 06 '16 19:07

Apolymoxic


1 Answers

This was solved by using an array to add the search items, and then run through the array and join them with a pipe.

The following is what was used:

 var whatsSelected = [];
 $.each($('.statusChk'), function () {
     if ($(this).is(":checked")) {
         whatsSelected.push('(?=.*' + $(this).val() + ')');
     }
 });

 $('#theTable').DataTable().search(whatsSelected.join('|'), true, false, true).draw();

The added string of (?=.* , then turning off the regex (? I think that's what the false does) was needed to make this work.

like image 168
Apolymoxic Avatar answered Sep 20 '22 02:09

Apolymoxic