Dynamically generate searchable sortable tables.

| May 7, 2010 | Reply

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(“

“);
document.write(““);
document.write(““);
document.write(“

“);

$(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 });

Tags: ,

Category: Uncategorized

About the Author ()