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.

[code lang=”js”]

* 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).ready(function() {
// Before the FilterTable, put the search filter.

// Convert the existing table into a grid.
widthFixed: false,
widgets: [‘zebra’]
}) ;

// Highlight hovered row.
$(‘tbody tr’).hover(function(){
}, function(){

//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

//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

This entry was posted in Code.

Post a Comment

You must be logged in to post a comment.