Using jQuery to filter a table

November 25, 2009

jQuery is simply awesome. I recently wanted to filter a table to only show tasks that were assigned to me. With jQuery this is really simple.


<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js">
</script>
<script type="text/javascript">
$(function(){
// hide rows that do not mention 'John' in the 2nd column
$('#tasks>
tr>td:nth-child(2)')
.not(':contains("John")')
.parent()
.hide();
});
</script>

<table id="tasks">
<tr>
<th scope="col">Task</th>
<th scope="col">Entered by</th>
<th scope="col">Assigned to</th>
</tr>
<tr>
<td>Pick fantasy football team</td>
<td>John</td>
<td>John</td>
</tr>
<tr>
<td>Buy lunch</td>
<td>John</td>
<td>John</td>
</tr>
<tr>
<td>Write blog post</td>
<td>John</td>
<td>John</td>
</tr>
<tr>
<td>Make tea</td>
<td>John</td>
<td>Simon</td>
</tr>
<tr>
<td>Get biscuits for CFUG</td>
<td>Andy</td>
<td>Andy</td>
</tr>
<tr>
<td>Add task filtering</td>
<td>Simon</td>
<td>John</td>
</tr>
<tr>
<td>Style tasks table</td>
<td>Simon</td>
<td>Andy</td>
</tr>
<tr>
<td>Schedule meeting</td>
<td>Andy</td>
<td>Simon</td>
</tr>
</table>

Awesome!


2 comments

  1. What would be very clever is if you could extend the table headers (TH) with a link to allow each to be filtered based on any one of the items in that column (I've seen this in Excel).

    My mind is already writing the code. How can I trickle this into the current project at work... :)

    Comment by Bernhard – November 25, 2009
  2. Simple and easy to understand......
    Good One....

    Comment by Veerendranath Darsi – February 11, 2010

Leave a comment

If you found this post useful, interesting or just plain wrong, let me know - I like feedback :)

Please note: If you haven't commented before, then your comments will be moderated before they are displayed.