The Mighty Blog

Using jQuery to Search an HTML Table

Sep 24

Written by:
9/24/2009  RssIcon

Whenever I provide a listing of records, I always provide a way to search those records.  Typically, the chosen display for these records comes in the form of an HTML table.  My search usually consists of a little T-SQL magic in a stored procedure, which would require a PostBack of some kind to the web server to retrieve the filtered records.  This has never been efficient.  While thinking of this concept earlier today, I had an epiphany.  Why not use jQuery?

I could use jQuery to search the records in one of two ways.  First, the obvious way is to use the built-in AJAX feature in jQuery to perform the search on the database, and then return just the data needed to change the HTML mark-up on the fly.  While that is cool, my current listing of records is not that large.  I wanted a faster solution.

I chose to instead use jQuery to filter out the rendered HTML table rows that do not match the given query.  Since jQuery has an extensive and flexible selection of selectors, this was going to be both fun and easy!

I remembered that the jQuery library has a :contains(text) selector that allows you to select HTML tags by checking to see if the tag contains the given text.  For instance, the example below uses the contains selector to highlight the bullet with DotNetNuke® in the bullet.

  • ASP.Net
  • JavaScript
  • T-SQL
  • VB.Net
  • DotNetNuke

The jQuery code necessary to make that happen is a single line of code:

jQuery('li:contains(\'DotNetNuke\')').css('color', '#0000ff').css('font-weight', 'bold');

Pretty cool, huh?  Kind of.  Unfortunately, I found out the hard way that the :contains(text) selector is case-sensitive.  Thinking about the previous example, this means that using “dotnetnuke” in the contains selector would not have worked.  Fortunately, I found a great blog post by Rick Strahl that gave a case-insensitive version of the selector.  It worked like a charm!  (And also showed me the fact that my idea wasn’t new. D’oh!)

An Example

Expanding on this standard functionality, I created an HTML table with a listing of data records, and a search box above it to filter the results.  When you enter text into the textbox, the table automatically filters out rows that do not contain the text you’re searching for.  Here’s an example:

Search:   Cancel Search

First Last Address City State
John Dough 123 Main Street Orlando Florida
Jane Dough 4367 South Washington Avenue Bartow California
Bart Thompson 531 Townsend Circle Atlanta Georgia
Sherry Simpson 3346 Presario Lane, Apt. 123 Seattle Washington
Matt Damon 300 Pounds Street Boston Massachusetts

I don’t know about you, but I think that’s AWESOME!  Some features that I had put into this initially was a dynamic cancel search image, cancel search by pressing ESC, and displaying a message when the search has no results.

The Code Review

It was actually quite easy.  Here is a breakdown of the code used to make this happen.  (Make sure you look in the code comments to have an explanation of what I am doing and why.)

First, I created a function to reset the search, that could be used in a number of places as needed.

function resetSearch() {
    // clear the textbox
    jQuery('#txtSearch').val('');
    // show all table rows
    jQuery('#tblSearch tr').show();
    // remove any no records rows
    jQuery('.norecords').remove();
    // remove the cancel search image
    jQuery('#imgSearch').hide();
    // make sure we re-focus on the textbox for usability
    jQuery('#txtSearch').focus();
}

Next, I wrapped all of my code in a .ready() block to make sure it executes when it is supposed to, beginning with the initial steps to set-up the UI.

// hide the cancel search image
jQuery('#imgSearch').hide();
 
// reset the search when the cancel image is clicked
jQuery('#imgSearch').click(function() {
    resetSearch();
});
 
// cancel the search if the user presses the ESC key
jQuery('#txtSearch').keyup(function(event) {
    if (event.keyCode == 27) {
        resetSearch();
    }
});

Now that I had everything set-up, I was able to write the real magic of the search.  This is where the search gets executed and handled.  This is also in the.ready() block.

// execute the search
jQuery('#txtSearch').keyup(function() {
    // only search when there are 3 or more characters in the textbox
    if (jQuery('#txtSearch').val().length > 2) {
        // hide all rows
        jQuery('#tblSearch tr').hide();
        // show the header row
        jQuery('#tblSearch tr:first').show();
        // show the matching rows (using the containsNoCase from Rick Strahl)
        jQuery('#tblSearch tr td:containsNoCase(\'' + jQuery('#txtSearch').val() + '\')').parent().show();
        // show the cancel search image
        jQuery('#imgSearch').show();
    }
    else if (jQuery('#txtSearch').val().length == 0) {
        // if the user removed all of the text, reset the search
        resetSearch();
    }
 
    // if there were no matching rows, tell the user
    if (jQuery('#tblSearch tr:visible').length == 1) {
        // remove the norecords row if it already exists
        jQuery('.norecords').remove();
        // add the norecords row
        jQuery('#tblSearch').append('<tr class="norecords"><td colspan="5" class="Normal">No records were found</td></tr>');
    }
});

The Full Code Snippet

Here is the full snippet of code that you can use to try this yourself.

<html>
<head>
    <title>Untitled</title>
    <script language="javascript" type="text/javascript" src="/Resources/Shared/Scripts/jquery/jquery.min.js"></script>
   1:  
   2: </head>
   3: <body>
   4:     <p style="text-align:right;width:500px;">
   5:         <span style="font-weight:bold;">Search:</span> <input type="text" id="txtSearch" name="txtSearch" maxlength="50" />&nbsp; 
   6:         <img id="imgSearch" src="/images/cancel.gif" alt="Cancel Search" title="Cancel Search" style="width:150px;width:14px;height:14px;" />
   7:     </p>
   8:     <table id="tblSearch" cellpadding="2" cellspacing="0" border="1" style="width:500px;">
   9:         <tr style="font-weight:bold;">
  10:             <td>First</td>
  11:             <td>Last</td>
  12:             <td>Address</td>
  13:             <td>City</td>
  14:             <td>State</td>
  15:         </tr>
  16:         <tr>
  17:             <td>John</td>
  18:             <td>Dough</td>
  19:             <td>123 Main Street</td>
  20:             <td>Orlando</td>
  21:             <td>Florida</td>
  22:         </tr>
  23:         <tr>
  24:             <td>Jane</td>
  25:             <td>Dough</td>
  26:             <td>4367 South Washington Avenue</td>
  27:             <td>Bartow</td>
  28:             <td>California</td>
  29:         </tr>
  30:         <tr>
  31:             <td>Bart</td>
  32:             <td>Thompson</td>
  33:             <td>531 Townsend Circle</td>
  34:             <td>Atlanta</td>
  35:             <td>Georgia</td>
  36:         </tr>
  37:         <tr>
  38:             <td>Sherry</td>
  39:             <td>Simpson</td>
  40:             <td>3346 Presario Lane, Apt. 123</td>
  41:             <td>Seattle</td>
  42:             <td>Washington</td>
  43:         </tr>
  44:         <tr>
  45:             <td>Matt</td>
  46:             <td>Damon</td>
  47:             <td>300 Pounds Street</td>
  48:             <td>Boston</td>
  49:             <td>Massachusetts</td>
  50:         </tr>
  51:     </table>
  52:     <script language="javascript" type="text/javascript">
  53:         jQuery.expr[":"].containsNoCase = function(el, i, m) {
  54:             var search = m[3];
  55:             if (!search) return false;
  56:             return eval("/" + search + "/i").test($(el).text());
  57:         };
  58:  
  59:         jQuery(document).ready(function() {
  60:             // used for the first example in the blog post
  61:             jQuery('li:contains(\'DotNetNuke\')').css('color', '#0000ff').css('font-weight', 'bold');
  62:  
  63:             // hide the cancel search image
  64:             jQuery('#imgSearch').hide();
  65:  
  66:             // reset the search when the cancel image is clicked
  67:             jQuery('#imgSearch').click(function() {
  68:                 resetSearch();
  69:             });
  70:  
  71:             // cancel the search if the user presses the ESC key
  72:             jQuery('#txtSearch').keyup(function(event) {
  73:                 if (event.keyCode == 27) {
  74:                     resetSearch();
  75:                 }
  76:             });
  77:  
  78:             // execute the search
  79:             jQuery('#txtSearch').keyup(function() {
  80:                 // only search when there are 3 or more characters in the textbox
  81:                 if (jQuery('#txtSearch').val().length > 2) {
  82:                     // hide all rows
  83:                     jQuery('#tblSearch tr').hide();
  84:                     // show the header row
  85:                     jQuery('#tblSearch tr:first').show();
  86:                     // show the matching rows (using the containsNoCase from Rick Strahl)
  87:                     jQuery('#tblSearch tr td:containsNoCase(\'' + jQuery('#txtSearch').val() + '\')').parent().show();
  88:                     // show the cancel search image
  89:                     jQuery('#imgSearch').show();
  90:                 }
  91:                 else if (jQuery('#txtSearch').val().length == 0) {
  92:                     // if the user removed all of the text, reset the search
  93:                     resetSearch();
  94:                 }
  95:  
  96:                 // if there were no matching rows, tell the user
  97:                 if (jQuery('#tblSearch tr:visible').length == 1) {
  98:                     // remove the norecords row if it already exists
  99:                     jQuery('.norecords').remove();
 100:                     // add the norecords row
 101:                     jQuery('#tblSearch').append('<tr class="norecords"><td colspan="5" class="Normal">No records were found</td></tr>');
 102:                 }
 103:             });
 104:         });
 105:  
 106:         function resetSearch() {
 107:             // clear the textbox
 108:             jQuery('#txtSearch').val('');
 109:             // show all table rows
 110:             jQuery('#tblSearch tr').show();
 111:             // remove any no records rows
 112:             jQuery('.norecords').remove();
 113:             // remove the cancel search image
 114:             jQuery('#imgSearch').hide();
 115:             // make sure we re-focus on the textbox for usability
 116:             jQuery('#txtSearch').focus();
 117:         }
 118:     
</script>
</body>
</html>

Technorati Tags: ,

Tags:
Categories: ASP.Net

37 comment(s) so far...


Gravatar

Re: Using jQuery to Search an HTML Table

Hi Mr Will Strohl
your code is so enjoyable because there was a question in my mind " How can I filter table data in client side.I will be so thankful if you help me to find out how can I set the selected (onclick) row as the first row in html table using Query ( or javascript ).may I ask you how can I do it ? ( please send to me the sample code or put it's on your blog as I can download it .
best regards

By Ahmad Ali on   11/4/2009
Gravatar

Re: Using jQuery to Search an HTML Table

Thanks, Ahmad. I hope I understand your request, because I blogged about it tonight. Here is relocate a table row using jQuery.

By Will on   11/4/2009
Gravatar

Re: Using jQuery to Search an HTML Table

Hi Will Strohl,
Thanks a lot for the ossum code..It saved my day!!

By mag on   11/23/2009
Gravatar

Re: Using jQuery to Search an HTML Table

I am happy to help! :)

By Will on   11/23/2009
Gravatar

Re: Using jQuery to Search an HTML Table

Hi,
The example is very nice.. The above example sort/filter entire row, is it possible to sort/filter individual cells???? I am having a html page with 5 columns and 20 rows and an input field above the table (same as above example). When i search for a data from the table, the cells which matches the query, should form in a row, once the 5 columns filled, it should align in 2nd row...Here is an example..

a |b |c |d |e |
f |r |q |y |b |
b |g | k |w | a|

When ever i search for "b", the result should be in below table format:
b | b | b |

The result should form in 5 columns, if the search result is more than 5, it should align in 2nd row...

Regards,
Chandru..

By Chandu on   8/16/2010
Gravatar

Re: Using jQuery to Search an HTML Table

What I did was a simple proof of concept really, to fill a very limited project scope. When you begin to get more complicated, you're really better off finding and using a grid. Most of them render from tables too.

By Will on   8/16/2010
Gravatar

Re: Using jQuery to Search an HTML Table

Hi Will Strohl,

Thank for quick reply.. I don't have command over programming... I am getting the examples, which will sort entire row, but not what i am looking for...

Regards,
Chandru

By Chandru on   8/17/2010
Gravatar

Re: Using jQuery to Search an HTML Table

hi, why doesn't the full-code snippet work on a local machine, even after removing the line numbers and with the right path of jquery file ?

By Ray on   9/12/2010
Gravatar

Re: Using jQuery to Search an HTML Table

@Ray: I couldn't answer that for you. It obviously works here. Try comparing the source of this page to yours. Other than that, there are any number of things that could have gone wrong in your implementation. Believe me. I am sure I've run into them all myself. :)

By Will on   9/12/2010
Gravatar

Re: Using jQuery to Search an HTML Table

Thanks Will, it works. That was my mistake ... one of the script wasn't in ready().

By Ray on   9/15/2010
Gravatar

Re: Using jQuery to Search an HTML Table

I am happy to help (when I can). :)

By Will on   9/15/2010
Gravatar

Re: Using jQuery to Search an HTML Table

Hey ,

I need one help ,I have find word in table(That ) and highlight ,complete row ,which contains that word .
How we can do this

Thanks

By Gyan on   11/19/2010
Gravatar

Re: Using jQuery to Search an HTML Table

@Gyan: Unfortunately, I am not sure what your message was in regards to. :(

By Will on   11/18/2010
Gravatar

Re: Using jQuery to Search an HTML Table

Hi.

When I insert the code in Dreamweaver I recieve an error on this line of code:

elseif (jQuery('#txtSearch').val().length == 0) {

Do You have any idea how to fix this?

By Jim on   11/27/2010
Gravatar

Re: Using jQuery to Search an HTML Table

@Jim: I haven't used Dreamweaver in a long time. It probably doesn't like something about the syntax. Not sure what though.

By Will on   11/27/2010
Gravatar

Re: Using jQuery to Search an HTML Table

I am also having trouble getting this to run on my local machine. I copied your code over and removed all of the line numbers. I also pointed it to googles copy of jQuery and it is still not working :-/. Is there something else I need to modify in your full code snippet?
Thanks in advance

By JJ on   11/30/2010
Gravatar

Re: Using jQuery to Search an HTML Table

I get the following error from the Firefox error console
Error: jQuery is not defined
Source File: file:///C:/Documents%20and%20Settings/user/My%20Documents/Site/test.html
Line: 113

By JJ on   11/30/2010
Gravatar

Re: Using jQuery to Search an HTML Table

I figured it out!!! Your code snippet has


there needs to be a space between script and laguage
as soon as I did that it worked! :)

By JJ on   11/30/2010
Gravatar

Re: Using jQuery to Search an HTML Table

@JJ: Glad you have it figured out. It's important to note that on any site that has pre-formatted code, there is a great potential to have odd typos that result from the code formatting tool.

By Will on   11/30/2010
Gravatar

Re: Using jQuery to Search an HTML Table

I am not sure what i am doing wrong but I cannot get this to work locally for me. I have jQuery Minified 1.4.4 stored locally and have corrected the "scriptlanguage" to "script language" as well as "elseif" to "else if" but for some reason this doesn't work. Any chance a quick review my sample of the code found here could be looked at? I'm sure its something small... i see no reason that this shouldn't work with the html file, image file, and js file all stored in same directory...

pastebin.com/idCdx0bv

By wraithe on   12/16/2010
Gravatar

Re: Using jQuery to Search an HTML Table

@Wraithe: Unfortunately, I don't really have time to troubleshoot your code for you. The best example you can possibly have is the HTML source for this page. Check that out, and compare it to your own code.

By Will on   12/16/2010
Gravatar

Re: Using jQuery to Search an HTML Table

Thanks Will. Not sure why but for some reason it has started working on its own without any change to the code.

The only drawback to this script is when its used with a large table. (e.g. my instance of 15,000+ records), the lag in processing the search (being client-side) is pretty insane. Never-the-less the function works great otherwise. Thanks for the post.

By wraithe on   12/24/2010
Gravatar

Re: Using jQuery to Search an HTML Table

@Wraithe: Sounds like a caching issue originally then. This solution isn't meant to scale. For tables that large, you should really be showing subsets of data with an AJAX back-end.

By Will on   12/24/2010
Gravatar

Re: Using jQuery to Search an HTML Table

Thanks for a nice, clear write up and working example. Saved me a lot of time.

By Charles Severabce on   1/10/2011
Gravatar

Re: Using jQuery to Search an HTML Table

Brilliant Script, thanks for this. Just a quick note by way of help to anyone trying to get this to work. I found the only was to get this script to work was to use a hosted version of jquery.min.js. Maybe the latest version downloaded has a problem with this script? I don't know.

Another schoolboy error I made was not to have the table ID=tblSearch included in my table definition. The Script can't find the table unless you do this.

By David on   2/17/2011
Gravatar

Re: Using jQuery to Search an HTML Table

@David: Thank you very much. There is always potential for scripts to break or work differently and faster/slower as time and updates come into play. :)

By Will on   2/17/2011
Gravatar

Re: Using jQuery to Search an HTML Table

I want to filter rows that contain text scheduel
For example
col1 col2 col3
1 a schedule
2 b unschedule
now i want to filter rows containing text schedule and complete row colorfull .
thnx in advance.

By ali on   3/7/2011
Gravatar

Re: Using jQuery to Search an HTML Table

@Ali: The examples are in the blog post and sample code. You would simply have to update the UI and code to account for the advanced level of filtering that you are looking for.

By Will on   3/7/2011
Gravatar

Re: Using jQuery to Search an HTML Table

Any way to change the search parameters to look for a range?

I.E. - search for $74.00

shows range of $74 - $80

Thanks in Advance.

By Joe on   6/23/2011
Gravatar

Re: Using jQuery to Search an HTML Table

@Joe: Of course there is, but it would require modifying the search to do so. There is much more that could possibly be added to the resulting changes, depending on the scope of what you want to do. At the core of this, you would probably need to specify certain columns to search for, or filter on value type, which requires a much less elegant and less performing solution - as you would need to read and compare each value individually.

By Will on   6/27/2011
Gravatar

Search based on the value but should exclude one column in some scenario

Hi.
i am new to this jQuery and also my project. I have assigned the task to include a filter condition but it should exclude one column in some scenario. Means '2nd column' should not include for search case.

where i have to include the exclude function
like this is correct?

jQuery('#tblSearch tr td:not('second-child'):containsNoCase(\'' + jQuery('#txtSearch').val() + '\')')

#2 : where can i include the sorting functionality. user need to sort the data.. In this case where should i call jQuery.sortable= true.

Because they used ur code only.

Thanks in advance.

saravanan S

By saravanan on   11/18/2011
Gravatar

Search based on the value but should exclude one column in some scenario

Hi.
i am new to this jQuery and also my project. I have assigned the task to include a filter condition but it should exclude one column in some scenario. Means '2nd column' should not include for search case.

where i have to include the exclude function
like this is correct?

jQuery('#tblSearch tr td:not('second-child'):containsNoCase(\'' + jQuery('#txtSearch').val() + '\')')

#2 : where can i include the sorting functionality. user need to sort the data.. In this case where should i call jQuery.sortable= true.

Because they used ur code only.

Thanks in advance.

saravanan S

By saravanan on   11/18/2011
Gravatar

Exclude one column and include sorting functionality

Hi.

How to exclude one column in the search for some scenario & how can i call sort.

By saravanan on   11/18/2011
Gravatar

Re: Using jQuery to Search an HTML Table exclude one column

Hi

here how to exclude one column and add sorting , filtering functions

By saravanan on   11/19/2011
Gravatar

Re: Using jQuery to Search an HTML Table

Do you think this be adapted and combined with

www.switchonthecode.com/tutorials/xml-parsing-with-jquery

providing a searchable table/listing from a XML feed?

By Carlito on   12/1/2011
Gravatar

Re: Using jQuery to Search an HTML Table

thank.. it's code very help me to search data.

By Shen on   1/3/2012
Gravatar

Re: Using jQuery to Search an HTML Table

Really terrific tutorial -- works beautifully! Thanks!

By G on   1/27/2012

Your name:
Gravatar Preview
Your email:
(Optional) Email used only to show Gravatar.
Your website:
Title:
Comment:
Add Comment   Cancel 
Add to Technorati Favorites
Tweet about my blog
The opinions expressed here are the personal opinions of Will Strohl and do not necessarily represent the views and opinions of the DotNetNuke Corporation.
© Copyright 2004-2011 by Will Strohl. All rights reserved. Website Skinned By: Ralph Williams  Website Hosted By: Applied Innovations