Holt59 / datatable

Javascript Plugin for data tables creation
http://holt59.github.io/datatable/
MIT License
108 stars 42 forks source link

Question: How to search/filter multiple columns with one search field #41

Closed Thornore closed 5 years ago

Thornore commented 5 years ago

I am attempting to search multiple table columns with one search field. The table is built on the page prior to initilizing datatable so I am guessing the data key is based upon the column number...

I first setup the filters for certain columns and simply added a listener to my search field to populate each column's filter field and triggered them but this only results in removing all data because the search term cannot be found in all of the columns.

I am guessing it is possible with the documented "lambda" filter but the terminology used is a bit confusing to me and difficult to implement. Upon further exploration I am just curious if it is even possible and if so could you give me a bit more of a project direct example?

I have a table with 5 columns and simply want to search the first, third, fourth, and fifth coulmns with a certain search term. I would like for it to show all rows that have at least one match in any of those 4 columns.

Thank you for your help, attention, and time... in answering my questions and for providing the datatable javascript.

Holt59 commented 5 years ago

This is possible, what you want to do is something like:

filters: {
    _1: function (data, text) {
        for (var i = 0; i < data.length; ++i) {
            // text is always uppercase, you can obviously perform different checks.
            if (new String(data[i]).toUpperCase().indexOf(text) !== -1) {
                return true;
            }
        }
        return false;
    }    
}

The _1 key is what you want here for the lambda, this should give you an input filter on the first column. The easiest way if you want to move it / make it span multiple column is to do it after the datatable via JS. data will contains the whole row, which in your case is a standard JS array.

I cannot test this code right now, so it may not work out-of-the-box, but you get the idea! Feel free to ask if you need more information.

Thornore commented 5 years ago

Thank you very much for your reply and solution. I did, however, write my own search function in the meantime that iterates the entire data array, re-assigns it to the table's data array, refreshes the table, and then resets the per page option. It seems to work fine...