Searching a table with jQuery

A couple of weeks ago I looked into creating a generator that would output the php-code needed to embed javascript libraries hosted by cdnjs.com. As a part of doing this, I needed to create a searchable table that would filter rows as I typed. Since this table would hold a lot of data, it needed to be efficient.

In my case I had a lot of information that I wanted to be included when searching. To keep things simple I simply decided to add all these value in a attribute, which I called “data-keywords”. In other words, it doesn’t search the rows, but it searches the attribute. The rows would look like this:

<tr data-keywords="moment.js moment.min.js date moment time">....</tr>

Now, the javascript code would need to do a couple of things. First off, it would have to update the table for each keystroke I entered in the search box. Secondly, it would have to filter the data by matching it against the “data-keywords” attribute. As a third criteria I wanted this script to constantly make sure to style odd and even rows, which meant adding and removing classes constantly. The code below shows you how I did this with only a few lines of code. (see the script in action here)

jQuery(function($){
    //index the dom elements
    var $list = $('#table > tr'),
        $search = $('#search-input');

    //filter the rows when searching
    $search.on('keyup',function(event){
        //get the search criteria
        var val = jQuery(this).val().toLowerCase();

        //show all rows if search is empty, or only matched rows
        if(val == "") $list.show();
        else $list.filter(':not([data-keywords*="'+val+'"])').hide().end()
                  .filter('[data-keywords*="'+val+'"]').show();

        //add and remove class for alternating rows
        $list.filter(':not(:visible:even)').removeClass('alternate').end()
             .filter(':visible:even').addClass('alternate');
    });
});

I'm a webdeveloper based in Oslo, Norway. I currently work with web development at Nettmaker.

I would like to change the world, but they won't give me the source…

3 Comments

Hi, I get the error below when trying to implement your script

TypeError: $search.on is not a function

Hi! Perhaps you are using an older version of jQuery? The “on()” handler requires jQuery 1.7 or above. You can alternatively use “$search.keyup(function(event){” instead.

Leave a Reply

Your email address will not be published. Required fields are marked *