Before sometime I had written a post on jQuery case-insensitive expression filter. Now today we will learn about how to put simple filter for our HTML table using jQuery and it's case-insensitive expression.

It's takes just few lines of Javascript / jQuery code to implement quick filter for an HTML table, here you go:

The HTML

 
<label for="kwd_search">Search:</label>
<input type="text" id="kwd_search" value=""/>
<table id="my-table" border="1" style="border-collapse:collapse">
<thead>
<tr>
<th>Name</th>
<th>Sports</th>
<th>Country</th>
</tr>
</thead>
<tbody>
<tr>
<td>Sachin Tendulkar</td>
<td>Cricket</td>
<td>India</td>
</tr>
<tr>
<td>Tiger Woods</td>
<td>Golf</td>
<td>USA</td>
</tr>
<tr>
<td>Maria Sharapova</td>
<td>Tennis</td>
<td>Russia</td>
</tr>
</tbody>
</table>
 


The Javascript

 
// When document is ready: this gets fired before body onload <img src='http://blogs.digitss.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />
$(document).ready(function(){
	// Write on keyup event of keyword input element
	$("#kwd_search").keyup(function(){
		// When value of the input is not blank
		if( $(this).val() != "")
		{
			// Show only matching TR, hide rest of them
			$("#my-table tbody>tr").hide();
			$("#my-table td:contains-ci('" + $(this).val() + "')").parent("tr").show();
		}
		else
		{
			// When there is no input or clean again, show everything back
			$("#my-table tbody>tr").show();
		}
	});
});
// jQuery expression for case-insensitive filter
$.extend($.expr[":"],
{
    "contains-ci": function(elem, i, match, array)
	{
		return (elem.textContent || elem.innerText || $(elem).text() || "").toLowerCase().indexOf((match[3] || "").toLowerCase()) >= 0;
	}
});
 

That's all it takes to put a quick filter using jQuery, see a live working demo here.

Similar Posts: