A few weeks ago, I was looking for a way to filter records in a table. The screen that I was going to use this one was a composite/advanced search screen to where after the results are populated, the user can continue typing in search results into other fields and it would auto-filter.
There are a large amount of jQuery plug-ins that offer table filtering features. I reviewed the TableSorter plug-in; however, I didn't want a filtering system where 1 text box would filter all columns. That plug-in works extremely well and I am using it in other areas, but I'm looking for a text box-to-column filtering mechanism instead. Bill Beckelmen, who has a lot of great posts and examples on the TableSoter plug-in, suggested trying the jQuery Column Filter or tablefilter plug-ins. Both were better; however, also auto-created the text boxes in another header row for the table. After looking a bit more, I came to the conclusion that I would need to write my own functionality. If I continue working on refining this code, I will probably see about turning it into a plug-in for easier use.
The filterColumn Function:
Inside of the filterColumn function, 3 things occur to make the filtering mechanism work. First, the two input parameters are inserted into regular expression patterns that will be used to locate the table column header as well as the records in that column once found. The second thing it does is loop through the column header (first table row in the thead tag that contains th tags...or "#resultsTable thead tr:first th" in jQuery selector syntax) to locate the column's index. Lastly, it loop through the table's records using the column's index and sets the row's display style to "none" if it doesn't match the filtering criteria.
I have a lot of refinement to go on this function if I am thinking about converting it into a plug-in at some point. I need to make the table's id not hard coded and bind the onKeyUp events when the search button is pressed instead of having it attached all the time in the HTML. In addition, I need to look into incorporating a zebra-striping plug-in as well to have it address the row styling after the filtering.
The code is a great starting point and it's very useful as is. With a little refinement, it can provide a very robust mechanism for simple table filtering without having to learn and use a very complex plug-in.