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:

$.fn.tableFilter = function(tableSelector) {

    table = $(tableSelector);   

    updateTable = function() {

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

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

    }

    $(this).keyup(updateTable);

}

The we just wire up our plugin like this

$("#filter").tableFilter("#ProductGrid");

View the plugin in action here.

Note that this is case sensitive.  You can see how to add a case insensitive selector here: 
http://www.ericmmartin.com/creating-a-custom-jquery-selector/.
Ann Arbor Day of .NET code and slides
Ann Arbor Day of .NET is a blast.

Here's just a quick update to share my code and slides from my talk, Browser Magic with jQuery.

Slides

Demo 1 (Filtering a table of Northwind Products)

Demo 2 (Adding AJAX to an existing MVC application)


I swear I'll actually update this blog with more in depth posts about my demos within the week.