Reputation: 849
I try to use https://datatables.net/reference/api/filter() but no effect. I would like to filter column by clicking checkbox.
Code:
var table = $('#table').DataTable();
var filteredData = table
.column( 0 )
.data()
.filter( function ( value, index ) {
return value > 4000 ? true : false;
} );
$("#show_only_packed").click(function() {
if ($(this).is(":checked")) {
filteredData.draw();
}
});
Actually I used search()
but I wanna understand how to use filter()
$("#show_only_packed").click(function() {
if ($(this).is(":checked")) {
table.column( 3 ).search( 'Spakowano' ).draw();
} else {
table.column( 3 ).search('').draw();
}
});
Upvotes: 1
Views: 3944
Reputation: 17849
Well, the filter()
should not be confused with the search()
function. The filter()
actually does not produce any direct output on your table, but can manipulate data behind the scenes.
Suppose you have a list of people in your table with their age as one of the attributes. And your goal is to count the elder (over 60 years old) people in this set. Then this is easy using the filter like this:
var filteredData = table.column(3)
.data()
.filter(function (value, index) {
if (parseInt(value) > 60) {
eldersCount++;
}
});
Here we define our age column to be column number 3 (zero based index), and we do our manipulations...
Here is the fiddle
Upvotes: 1
Reputation: 58920
CAUSE
API method filter()
is often confused with search()
but it doesn't affect the table. It only returns filtered data according to the given condition.
SOLUTION
You need to use custom filtering instead.
For example:
$('#show_only_packed').on('click', function(){
if(this.checked){
$.fn.dataTable.ext.search.push(
function (settings, data, dataIndex){
return (data[0] > 4000) ? true : false;
}
);
}
table.draw();
if(this.checked){
$.fn.dataTable.ext.search.pop();
}
});
DEMO
See this jsFiddle for code and demonstration.
Upvotes: 4