Using jQuery to Filter Table Rows

15 09 2008

I’m retouching an old system, and though it could use a filter on it’s report page. The report has a large table with about 300 rows. After some play with jQuery, I came out with this little filter.
The project is using the .net GridView control, so I had limited control over the output HTML code. Still, I think this code can work for most tables. One thing to notice: you should use the class “filterable” on your table or on one of its parents for the code to work.
First, we need a text box:

Filter:
<input type="text" id="FilterTextBox" name="FilterTextBox" />

And the code:

$(document).ready(function(){
 //add index column with all content.
 $(".filterable tr:has(td)").each(function(){
   var t = $(this).text().toLowerCase(); //all row text
   $("<td class='indexColumn'></td>")
    .hide().text(t).appendTo(this);
 });//each tr
 $("#FilterTextBox").keyup(function(){
   var s = $(this).val().toLowerCase().split(" ");
   //show all rows.
   $(".filterable tr:hidden").show();
   $.each(s, function(){
       $(".filterable tr:visible .indexColumn:not(:contains('"
          + this + "'))").parent().hide();
   });//each
 });//key up.
});//document.ready

Explanation:

  1. Create Index Column – lines 2-7 – The jQuery “:contains()” selector is case sensitive, so at the first step I create another column on the table, than contains the whole row’s text on lowered case. On line 3 you may have noticed I’m filtering only rows that has <td>, to avoid hiding the header column (presumably, the header only has <th>). Later, I could make searches in this column alone. This works as long as the text on the table doesn’t change.
  2. Bind the Key-Up Event – lines 8-16.
  3. Make an array with all filter keywords – line 9 – Get all word from the text box and put them in an array. Again, I’m using toLowerCase() because “:contains” is case sensitive.
  4. Hide rows – lines 12-15 – I’m using jQurey’s each function to go through the array, and hiding all rows that don’t contain the current keyword (Assuming AND between all words).

That’s it. Now rows on our table can be filtered.


Actions

Information

5 responses

22 05 2009
3 09 2009
John Tellurian

This is nice! How would we assume OR instead of AND?

3 09 2009
Kobi

Thanks John!
For OR you’ll have to reverse the logic – hide all rows, and then show rows that contain each word.
Just replace .show() and :visible with .hide and :hidden (and vice versa).

4 09 2009
John Tellurian

I was close.

And also reverse the :contains( too ?

Thank you Kobi!

jQueriffic!

4 09 2009
Kobi

Good point – you’d want to display rows if they do contain the word.
Well, the good thing about jQuery is that there are only three lines doing the filtering – it’s easy to understand.
Thanks John!

Leave a comment