|
Page 1 of 2
jQuery Table Row Filtering
Earlier we examined sorting and paging as techniques for helping users focus on relevant portions of a table's data. We saw that both could be implemented either with server-side technology or with JavaScript. Filtering completes this arsenal of data arrangement strategies. By displaying to the user only the table rows that match a given criterion, we can strip away needless distractions.
We have already seen how to perform a type of filter, highlighting a set of rows.
Now we will extend this idea to actually hiding rows that don't match the filter.
We can begin by creating a place to put our filter buttons. In typical fashion, we insert these controls using JavaScript so that people without scripting available do not see the options:
$(document).ready(function() { $ ('table.filterable'). each(function() { var $table = $(this); $table.find ('th'). each(function (column ) { if ($(this).is('.filter-column')) { var $filters = $('</p> <div class="filters"> <h3>Filter by ' + $(this).text() + ':</h3> </div> '); $filters.insertBefore($table); } }); }); });
%24%28document%29.ready%28function%28%29%20%7B%20%0A%0D%0A%24%28%27table.filterable%27%29.each%28function%28%29%20%7B%20%0A%0D%0Avar%20%24table%20%3D%20%24%28this%29%3B%20%0A%0D%0A%24table.find%28%27th%27%29.each%28function%20%28column%29%20%7B%20%0A%0D%0Aif%20%28%24%28this%29.is%28%27.filter-column%27%29%29%20%7B%20%0A%0D%0Avar%20%24filters%20%3D%20%24%28%27%3C%2Fp%3E%0D%0A%3Cdiv%20class%3D%22filters%22%3E%0D%0A%3Ch3%3EFilter%20by%20%27%20%0A%0D%0A%2B%20%24%28this%29.text%28%29%20%2B%20%27%3A%3C%2Fh3%3E%0D%0A%3C%2Fdiv%3E%0D%0A%27%29%3B%20%0A%0D%0A%24filters.insertBefore%28%24table%29%3B%20%0A%0D%0A%7D%20%0A%0D%0A%7D%29%3B%20%0A%0D%0A%7D%29%3B%20%0A%0D%0A%7D%29%3B
We get the label for the filter box from the column headers, so that this code can be reused for other tables quite easily. Now we have a heading awaiting some buttons:

|