Table sorting using JQuery

Yesterday I posted about how I was using JQuery and Ajax to produce a loading message for a website I’ve been working on. A complication of the approach I took was that I was no longer able to use the Table Sorting and Filtering library by Matt Kruse that I have used in the past.

The issue, as far as I could tell, was that the table technically didn’t exist when the library tried to find it in the DOM (Document Object Model) to add its functionality. This is because the library expects the table to exist when the page loads. The table I wanted to sort is being generated as the result of an Ajax call, after the HTML page is loaded.

Fortunately for me there is a JQuery plugin called Tablesorter, released by Christian Bach. I discovered that I could bind this library to a table at any time. With this in mind I adjusted my code so that the library was bound to my table after the Ajax call completed. In this way the code I posted before became:


<script type="text/javascript">
<!--
jQuery(function($) {
$("#contentArea").load("test.php");
});

$().ajaxSend(function(r,s){
$("#contentLoading").show();
$("#summaryData").tablesorter();
});

$().ajaxStop(function(r,s){
$("#contentLoading").fadeOut("fast");
});

//-->
</script>

Where #summaryData is the id of the table I wanted to sort. I’ll still continue to use the library by Matt Kruse where I don’t need to use the JQuery library, simply because it is smaller in size than the JQuery and Tablesorter plugins combined. However the library by Christian Bach is certainly very useful when JQuery is being used for other things as well.

One Response to “Table sorting using JQuery”

  1. Using JQuery for an Ajax loading message (2) « Tech Explorer Says:

    [...] Because the Ajax call is returning a table I’m using the JQuery plugin called Tablesorter, released by Christian Bach to provide client side sorting on the table. I wrote more about using this plugin in an earlier post. [...]

Leave a Reply