How do I filter a DataTable programmatically?

How do I filter a DataTable programmatically?

gib65gib65 Posts: 29Questions: 13Answers: 0

Hello,

I'm experimenting with filtering on DataTables. I'm following along with this article:

https://datatables.net/reference/api/filter()

I've uploaded an exampe of what I'm trying to do here:

http://www.shahspace.com/JQueryDataTable/index.html

My filtering code looks like this:

var filteredData = dt.column(0).data().filter(function(value, index) { return value == 'A' ? true : false;
``` });

But the grid still shows all values (A's, B's, and C's in the first column).

I'm not sure if I'm supposed to do something with fitleredData, give it to the grid somehow.

Can anyone see what I'm doing wrong?

Answers

  • kthorngrenkthorngren Posts: 21,570Questions: 26Answers: 4,996

    The variable filteredData contains the filtered results which you can process however you like. It doesn't automatically update the table.

    You can do something like this to clear the table and apply the filtered data:

    table.clear();
    table.rows.add(filteredData);
    table.draw();
    

    So far your examples have been pretty basic but I would recommend using one of the options here to provide test cases. Using these options makes it easier for us to look at and make changes to if needed.

    Kevin

  • allanallan Posts: 63,871Questions: 1Answers: 10,522 Site admin

    Probably worth having a little read over the filter() documentation that you linked to again. Specifically it says:

    This method should not be confused with `-api search() which is used to search for records in the DataTable - i.e. the filter method does not change the rows that are displayed in the DataTable.

    The filter() method will never effect the display of the records in the table. You need to use search() for that, or custom search.

    Allan

  • gib65gib65 Posts: 29Questions: 13Answers: 0

    Thanks both,

    allan, I think you're right: search() is really the API function I'm looking for (and it works).

    Kevin, your method of clearing the table and supplying the filter results also works, but I get the error described at http://datatables.net/tn/4 (by the sounds of it, it's because the filter object I'm passing in does not match the table DOM object). But I think search() is what I want anyway so it doesn't matter.

    And yes, I'll post examples via one of the methods described in that link.

This discussion has been closed.