«

»

Print this Post

Dynamically generate searchable sortable tables.

Frequently throughout my pages I like to print out reports of data. The jquery tablesorter plugin is an excellent way to take this tabular data and make it sortable by column. However, since I do this so frequently, I wanted to create a script that would set up the plugin and add some other features, like an itunes like lazy search feature and highlighted hovered rows. So, on my pages, after my table is created I include the following javascript.

Note: This requires jquery and the jquery tablesorter plugin.


/*
 * Start out by building a search filter div. After the sort table is created
 * this will be placed on the page on top of it.
 */
document.write("<div id='searchfilter'>");
document.write("<input type='text' name='filter' value='' id='filter'/>");
document.write("<span class='ui-icon ui-icon-help' title='Begin typing to filter results. [ESC] to clear.'></span>");
document.write("</div>");

$(document).ready(function() {
    // Before the FilterTable, put the search filter.
    $('#searchfilter').insertBefore('#FilterTable');

    // Convert the existing table into a grid.
    $("table").tablesorter({
        widthFixed: false,
        widgets: ['zebra']
    }) ;

    // Highlight hovered row.
    $('tbody tr').hover(function(){
        $(this).find('td').addClass('hovered');
    }, function(){
          $(this).find('td').removeClass('hovered');
    });

   //Default each row to visible
   $('tbody tr').addClass('visible');

   $('#filter').keyup(function(event) {
        //if esc is pressed or nothing is entered
        if (event.keyCode == 27 || $(this).val() == '') {
            //if esc is pressed we want to clear the value of search box
            $(this).val('');

            //we want each row to be visible because if nothing
            //is entered then all rows are matched.
            $('tbody tr').removeClass('visible').show().addClass('visible');
        }
        //if there is text, lets filter
        else {
            filter('tbody tr', $(this).val());
        }//end if
    });

    //filter results based on query
    function filter(selector, query) {
      query =   $.trim(query); //trim white space
      query = query.replace(/ /gi, '|'); //add OR for regex query

      $(selector).each(function() {
        ($(this).text().search(new RegExp(query, "i")) < 0) ? $(this).hide().removeClass('visible') : $(this).show().addClass('visible');
      });
     }//end function
});

Permanent link to this article: http://www.lukemacneil.com/2010/05/07/dynamically-generate-searchable-sortable-tables/

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>