Apolymoxic
Apolymoxic

Reputation: 836

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??

Upvotes: 7

Views: 10368

Answers (2)

themhz
themhz

Reputation: 8424

It looks like it caches the search parameters until you execute the chained function draw(). Then it will send a call to the end point with the parameters in columns[n][data]: populated so you can handle them in your server side script.

I did something like this:

$("#ddlTeam").change(function () {
                   var val= this.value;
                   if(val>0){
                       $('#example').DataTable().columns(9).search($("#ddlDomObject").val());
                       $('#example').DataTable().columns(5).search(val).draw();
                    }else{
                       $('#example').DataTable().columns(5).search('').draw();
                    }

                });

Upvotes: 0

Apolymoxic
Apolymoxic

Reputation: 836

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.

Upvotes: 14

Related Questions