Search code examples
jquerydatatablesbootstrap-multiselect

Applying filter for column using multi select dropdown with checkbox in datatable


My question is based on this original fiddle: https://jsfiddle.net/x92c3qu2/

This is a kind of example I am looking for. But my problem is when any value is having special characters (say, round brackets), then the example doesn't work.

This is my code - almost similar to original link

    $('#dropdown').multiselect({
    onChange: function(element, checked) {

      var cities = $('#dropdown option:selected');

      var selected = [];
      $(cities).each(function(index, city) {
        selected.push([$(this).val()]);
      });

      var regex = selected.join("|");

      $('#table').DataTable().column(1).search(
        regex, true, false, true
      ).draw();
    }
  });
}); 

https://jsfiddle.net/x92c3qu2/110/ - edited fiddle by me

Now in this, if you select "(Paris) France", it does not show any result despite having record in a table.

(tried by changing search(regax,true,false,true) - but doesn't work.

If you select "Paris", it shows both records related to "Paris"- according to me which is wrong. It should show exact result when value selected from drop down.

Try selecting multiple values of with and without special characters - the result is weird.

Please let me know if any further clarifications required.


Solution

  • If you want the regex to match the exact string you have to encapsulate the search string with the ^ and the $ characters. If the string has to match the exact string anyway you can disable the smart option in the search method.

    There are two problems with the entry (Paris) France. In your sample you are pushing the value of the option element which is set to Paris_France but in your table the entry to look for is still (Paris) France, so you should change that. The second issue is that the ( is a special character in Regex which you should escape in this case consider something like this when adding the value:

    selected.push(['^(' + $(this).val().replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&') +')$']);

    I've edited your JS fiddle with my proposed changes.