Abbett.org

Filter a table client-side with jQuery

My current project at work involves a lot of time-consuming medical data retrieval that makes server-side filtering (by provider, by date, by department, by data type) unpractical. Given that we are forced to load large batches of data up-front, I figured this would be a great opportunity for client-side filtering.

Fortunately, jQuery (version 1.4.2) and a bit of ingenuity made it quite easy.

In the example below, I use e-mail messages as my data elements, and I have three possible filters: year, tag, and sender.

Each filter can be selected using a drop-down:

Drop-down filters

Upon selection, the e-mail list will automatically update to show only items matching the selected filters.

Filtered table of e-mails

The trick is this: each row in the table semantically describes its data using the class attribute. For example, a row containing an item from 2009, sent by Sarah, with the tag Inbox will describe itself thusly:

<tr class="year-2009 sent-sarah tag-inbox"> ... </tr>

The filter drop-downs have option values that correspond to those classes, plus a wildcard option with an asterisk as the value. Here's the year filter:

<select class="filter">
  <option value="*">All years</option>
  <option value="year-2010">2010</option>
  <option value="year-2009">2009</option>
  <option value="year-2008">2008</option>
  <option value="year-2007">2007</option>
</select>

Whenever a select element changes, jQuery springs into action. It collects all the non-wildcard filter values that have been chosen, concatenates 'em into a single selector, and then hides the right table rows. Just read along in the code—it's all nicely commented.

Add a comment

Please add a comment using your Twitter account. Don't have one? Sign up.