1

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();
    }
});

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for explain. What do you thing about my solution with search? I've simplified it: $("#show_only_packed").click(function() { var table_filter = table.column( 3 ).search('').draw(); if ($(this).is(":checked")) { table_filter.search( 'Spakowano' ).draw(); } });
@user3041764, search() API method is good for text-based search (search( 'Spakowano'), for more complex scenarios, such as data[0] > 4000 custom filtering should be used.
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.