13

I am using the DataTables javscript library and I'm trying to filter a row out based on if a numerical value is greater than 60.

I'm trying to follow this example: http://datatables.net/reference/api/filter%28%29

The filter code looks like this:

table
    .column( 3 )
    .data()
    .filter( function ( value, index ) {
        return value > 60 ? true : false;
    } )

The problem is all rows are still visible and no filtering has been done at all. Even if my function simply returns false all rows are still visible. What's going on here?

JSFiddle of example

http://jsfiddle.net/1hLcpr3x/

1 Answer 1

16

The example you're linking to is filtering the returning array of the data from the columns, not the rows themselves.

You can verify this by returning the content and logging it

var filteredArray = table.column( 3 )
                         .data()
                         .filter( function(value, index) {
                             return value > 60 ? true : false;
                         })
                         .draw();

console.log(filteredArray);

FIDDLE

This is what the filter method does, it filters the data when you return it with data(), not the rows.

To filter the rows in place, you'd hook into the DataTables plugin, more specifically $.fn.dataTableExt.afnFiltering, and do something like this

$.fn.dataTableExt.afnFiltering.push(
    function (oSettings, aData, iDataIndex) {
        return aData[3] < 60;
    }
);

FIDDLE

Documentation for DataTables filtering

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

3 Comments

I have multiple datatables on a page, how do I make sure my custom hooked filter only works with the one I want? Can I derive the table from the passed in settings object?
@CanÜrek - what do you mean it's not working? It filters out anyone with an age of 60 or more, and in the last fiddle there are no rows whith persons older than 59, so it's working just fine ?
sorry to comment this late... but $.fn.dataTableExt.afnFiltering.push is not working for me...I keep getting this Uncaught TypeError: Cannot read property 'push' of undefined in console..

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.