web developer
web developer

Reputation: 527

jQuery DataTable column filtering using multi-select options

For my application, I am using jQuery DataTable with materialize frame work. My table is having the following columns:

1.Name 2.Position 3.Office 4.Age 5.Date and 6.Salary

In that, I am dynamically creating a multi select filter for 'Office' and 'Age' column from the table response. I have tried my example in the following JSFiddle link.

JSFiddle

But filtering is only working for single option and for multi select filtering it is not working. Also there is no relationship between 'Office' and 'Age' filters, both are working individually.

How to fix this?

Upvotes: 3

Views: 19554

Answers (2)

Shruti Sharma
Shruti Sharma

Reputation: 1

The above code will not work to make an exact match. For example, if I have a countries drop down list having the 2 countries 'Sudan' and 'South Sudan' and I am looking for Sudan, the above solution will return me both countries not only one.

Upvotes: -1

rad11
rad11

Reputation: 1561

Try to separate the event of any change to select.

Try this:

$(document).ready(function (){
    var table = $('#example').DataTable({
       dom: 'lrtip',
        initComplete: function () {
          this.api().columns([2]).every( function () {
            var column = this;
            console.log(column);
            var select = $("#officeFltr"); 
            column.data().unique().sort().each( function ( d, j ) {
              select.append( '<option value="'+d+'">'+d+'</option>' )
            } );
          } );
           this.api().columns([3]).every( function () {
            var column = this;
            console.log(column);
            var select = $("#ageFltr"); 
            column.data().unique().sort().each( function ( d, j ) {
              select.append( '<option value="'+d+'">'+d+'</option>' )
            } );
          } );
          $("#officeFltr,#ageFltr").material_select();
       }
    });

    $('#officeFltr').on('change', function(){
        var search = [];

      $.each($('#officeFltr option:selected'), function(){
            search.push($(this).val());
      });

      search = search.join('|');
      table.column(2).search(search, true, false).draw();  
    });

    $('#ageFltr').on('change', function(){
        var search = [];

      $.each($('#ageFltr option:selected'), function(){
            search.push($(this).val());
      });

      search = search.join('|');
      table.column(3).search(search, true, false).draw();
    });
});

jsfiddle

Upvotes: 6

Related Questions