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
|
|
Then we want to get a reference to the table we’re going to filter:
|
|
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:
|
|
then, we’ll display the rows that match the text we’ve typed:
|
|
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 http://s116742794.onlinehome.us/jquery/tablefilter.htm
Note that this is case sensitive. You can see how to add a case insensitive selector here