|
jQuery Table Row Filtering |
|
Page 2 of 2
Filter Options
Now we can move on to actually implementing a filter. To start with, we will add filters for a couple of known topics. The code for this is quite similar to the author highlighting example from before:
var keywords = ['conference', 'release']; $. each(keywords, function (index, keyword ) { $('</p> <div class="filter"></div> ').text(keyword).bind('click', {'keyword': keyword}, function(event) { $table.find ('tbody tr'). each(function() { if ($('td', this).filter(':nth-child(' + (column + 1) + ')').text() == event.data['keyword']) { $(this).show(); } else if ($('th',this).length == 0){ $(this).hide(); } }); $(this).addClass('active').siblings().removeClass('active'); }).addClass('clickable').appendTo($filters); });
var%20keywords%20%3D%20%5B%27conference%27%2C%20%27release%27%5D%3B%20%0A%0D%0A%24.each%28keywords%2C%20function%20%28index%2C%20keyword%29%20%7B%20%0A%0D%0A%24%28%27%3C%2Fp%3E%0D%0A%3Cdiv%20class%3D%22filter%22%3E%3C%2Fdiv%3E%0D%0A%27%29.text%28keyword%29.bind%28%27click%27%2C%20%0A%0D%0A%7B%27keyword%27%3A%20keyword%7D%2C%20function%28event%29%20%7B%0A%0D%0A%24table.find%28%27tbody%20tr%27%29.each%28function%28%29%20%7B%20%0A%0D%0Aif%20%28%24%28%27td%27%2C%20this%29.filter%28%27%3Anth-child%28%27%20%2B%20%28column%20%2B%201%29%20%2B%20%0A%0D%0A%27%29%27%29.text%28%29%20%3D%3D%20event.data%5B%27keyword%27%5D%29%20%7B%20%0A%0D%0A%24%28this%29.show%28%29%3B%20%0A%0D%0A%7D%20%0A%0D%0Aelse%20if%20%28%24%28%27th%27%2Cthis%29.length%20%3D%3D%200%29%7B%20%0A%0D%0A%24%28this%29.hide%28%29%3B%20%0A%0D%0A%7D%20%0A%0D%0A%7D%29%3B%20%0A%0D%0A%24%28this%29.addClass%28%27active%27%29.siblings%28%29.removeClass%28%27active%27%29%3B%20%0A%0D%0A%7D%29.addClass%28%27clickable%27%29.appendTo%28%24filters%29%3B%20%0A%0D%0A%7D%29%3B
Starting with a static array of keywords to filter by, we loop through and create a button for each. Just as in the paging example, we need to use the data parameter of .bind() to avoid accidental closure problems. Then, in the click handler, we compare each cell against the keyword and hide the row if there is no match. We must check whether the row is a subheader, to avoid hiding those in the process. Both of the buttons now work as advertised:

Trackback(0)

|