John Smith
John Smith

Reputation: 6197

Bootstrap, datatable, result of filter method is ignored

I have the newest DataTable plugin. In document.ready:

$('#admin_users_table').DataTable().column(3).data().filter(function(v) {
  console.log(v+'         '+Math.random());
  return false;
});

it runs once when site loads, and logs the good values. Now, if I change a dropdown:

$('#admin_users_filter').change(function() {
  console.clear();
  $('#admin_users_table').DataTable().draw();
});

it wont work. Actually, the problem is no matter what the return is, it wont affect what rows gets draw and what are not.

Upvotes: 0

Views: 116

Answers (1)

davidkonrad
davidkonrad

Reputation: 85518

filter() is not a search function that takes effect on the table. Its purpose is to let you extract content of the table as a new API instance, not to filter content.

Example, console out all rows where column #3 starts with a certain letter, chosen via a <select> box :

$("#filter").change(function() {
    var that = this;
    var filteredValues = table.column(3).data().filter(function(value, index ) {
        return value.toLowerCase().substr(0,1) == that.value;
    })
    //console out all matches
    console.log(filteredValues);
})    

If you want to filter the table programmatically, and not want to use the builtin search() function, you can implement a custom filter. The below does exactly the same as the above, but this time the action happens on the table itself :

$("#search").change(function() {
  var that = this;  
  $.fn.dataTable.ext.search.push(
     function(settings, data, dataIndex) {
        return data[3].toLowerCase().substr(0,1) == that.value;
     }
  )    
  table.draw();
  //reset the custom filter 
  $.fn.dataTable.ext.search.pop();  
});

both examples here -> http://jsfiddle.net/khbt2hhm/

Upvotes: 1

Related Questions