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.
#1 by Dharmavirsinh Jhala on August 14, 2011 - 9:51 am
Quote
Forgot to mention but is inevitable that do not forget to include jQuery library.
#2 by chandishwar on November 7, 2011 - 6:44 pm
Quote
hi , it s nice i used this filter . it works nice.
now my requirement is combination filter.
i have to filter with to attributes. how can i do this?
eg:
in my app, i need to filter with based on date, time.
the resultant table should have the matching information of what i entered in date & time
#3 by Dharmavirsinh Jhala on January 15, 2012 - 10:16 pm
Quote
Hi, I guess you need to provide class="date-time" or something like that and then if you have filters like From and To Date filter, you will need to go one step ahead and parse date.
Try using php.js for datetime helper functions similar to PHP in Javascript.
I hope this helps.