|
jQuery Collecting Filter Options |
jQuery Collecting Filter Options from Content
Now we need to expand the filter options to cover the range of available topics in the table. Rather than hard-coding all of the topics, we can gather them from the text that has been entered in the table. We can change the definition of keywords to read:
var keywords = {}; $table.find('tbody tr td').filter(':nth-child(' + (column + 1) + keywords[$(this).text()] = $(this).text(); });
var%20keywords%20%3D%20%7B%7D%3B%20%0A%0D%0A%24table.find%28%27tbody%20tr%20td%27%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.each%28function%28%29%20%7B%20%0A%0D%0Akeywords%5B%24%28this%29.text%28%29%5D%20%3D%20%24%28this%29.text%28%29%3B%20%0A%0D%0A%7D%29%3B
This code relies on two tricks:
- By using a map rather than an array to hold the keywords as they are found, we eliminate duplicates automatically.
- jQuery's $.each() function lets us operate on arrays and maps identically, so no later code has to change. Now we have a full complement of filter options:

Reversing the Filters
For completeness, we need a way to get back to the full list after we have filtered it.
Adding an option for all topics is pretty straightforward:
$('</p> <div class="filter">all</div> ').click(function() { $table.find('tbody tr').show(); $(this).addClass('active').siblings().removeClass('active'); }).addClass('clickable active').appendTo($filters);
%24%28%27%3C%2Fp%3E%0D%0A%3Cdiv%20class%3D%22filter%22%3Eall%3C%2Fdiv%3E%0D%0A%27%29.click%28function%28%29%20%7B%20%0A%0D%0A%24table.find%28%27tbody%20tr%27%29.show%28%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%20active%27%29.appendTo%28%24filters%29%3B%20
This gives us an all button that simply shows all rows of the table again. For good measure we mark it as active to begin with.
Trackback(0)
|