October 2008 Entries
Writing a jQuery plugin to filter a table on keypress
I recently had a requirement to filter a table as the user was typing.

I was able to write a jQuery plugin to do this in just six lines of code.

I want to use jQuery to add a keyup handler to my search box, and target table(s) via a selector parameter.

First, in order to extend functionality onto a selector, we add a new function to $.fn


  $.fn.tableFilter = function(tableSelector) {


Then we want to get a reference to the table we're going to filter:

    table = $(tableSelector);


and we'll write a function that will actually perform the filtering:

  

    updateTable = function() {

 

now, on every keypress we need a blank slate.  lets hide all the rows besides the header:


        table.find('tr:gt(0)').hide();

then, we'll display the rows that match the text we've typed:


        table.find('td:contains("' + $(this).val() + '")').parents('tr').show();

    }


and we'll assign the keypress of event of our textbox to our new filterfing function:


    $(this).keyup(updateTable);

}

and bam!  we're done: