Daniela
Daniela

Reputation: 491

Datatables - filter applied to just some tables

In datatables, there's this filtering function

$.fn.dataTableExt.afnFiltering.push(function (oSettings, aData, iDataIndex)

that filters all tables.

I have two tables, and I need the filter to be applied to just one of the tables.

How do I let Datatables know that I just want to filter table1 and leave table2 as it was?

Upvotes: 2

Views: 2229

Answers (3)

Daniela
Daniela

Reputation: 491

I found an answer elsewhere that helped me:

https://stackoverflow.com/a/11545376/4896102

Just added this inside the function

//array with the tables IDs you want the filtering function to ignore
var allowFilter = ['yourTableId1', 'youTableId2'];

$.fn.dataTableExt.afnFiltering.push(function (oSettings, aData, iDataIndex) 
{
    // check if current table is part of the allow list
    if ($.inArray(oSettings.nTable.getAttribute('id'), allowFilter ) == -1 )
    {
       // if not table should be ignored
       return true;
    }
    //rest of the code
    return false;
});

This one worked for me, and it has the advantage you can use an array so you can ignore multiple tables when filtering.

Upvotes: 1

Eric Guan
Eric Guan

Reputation: 15992

Check out this snippet from the DataTables creator.

https://www.datatables.net/forums/discussion/16623/using-fn-datatableext-afnfiltering-push-to-filter-tables

$.fn.dataTableExt.afnFiltering.push(
    function(settings, aData, iDataIndex) {
        if (settings.nTable.id === 'myTableId') {
            // filter example
        } else {
            // ...
        }
    }
);

You can check for the id of the table you want to filter. It's not an official solution, but it works.

Upvotes: 2

David784
David784

Reputation: 7464

You can use the DataTables .search() and .draw() methods of the API. See the online documentation

var dt1 = $('#table1').DataTable();
dt1.search('search text').draw();

Also see working fiddle

As an addendum, I just want to mention that in the 1.10+ DataTables, there are two ways to initialize the table: .dataTable() and .DataTable(). The second one returns the new API, which is what I used above. If you use the first one, you can still retrieve the new API using $( selector ).dataTable().api(), as documented in the online documentation

Upvotes: 0

Related Questions