Quick example of table sorting with ColdFusion and jQuery

For a while now I’ve been meaning to take a look at table sorting via jQuery. I finally got a chance to play with it last night and write up a quick demo. My example makes use of Tablesorter, a jQuery plugin that adds (wait for it) table sorting to existing tables. Check the plugin’s web site for full documentation on options and demos. Here is a quick example of how easy this is to use.

I began with a simple ColdFusion query and table display:

<cfquery name="getArt" datasource="cfartgallery"> select artname, description, price, issold from art </cfquery> <table border="1"> <tr> <th>Art</th> <th>Description</th> <th>Price</th> <th>Sold</th> </tr> <cfoutput query="getArt"> <tr> <td>#artname#</td> <td>#description#</td> <td>#dollarFormat(price)#</td> <td><cfif issold>Yes<cfelse>No</cfif></td> </tr> </cfoutput> </table>

There isn't anything special here. I grab art records from the ColdFusion cfartgallery demo database and display the name, description, price, and sold properties. Now let's look at how easy it is to add in the sort.

First - you need to separate the header of the table from the rest of the data. This is done with the TBODY and THEAD tags.

<table border="1" id="mydata"> <thead> <tr> <th>Art</th> <th>Description</th> <th>Price</th> <th>Sold</th> </tr> </thead> <tbody> <cfoutput query="getArt"> <tr> <td>#artname#</td> <td>#description#</td> <td>#dollarFormat(price)#</td> <td><cfif isBoolean(issold) and issold>Yes<cfelse>No</cfif></td> </tr> </cfoutput> </tbody> </table>

Also note I added an ID to the table. As you know, most jQuery operations will require you to name the items you want to manipulate. Ok, so next up I add in the JavaScript libraries:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script> <script type="text/javascript" src="/jquery/jquery.tablesorter.min.js"></script>

Next - I enable the sorting:

<script> $(document).ready(function() { $("#mydata").tablesorter(); }); </script>

And um - that's it! Considering that I normally have jQuery included already, I only needed to a) add tbody, theader, and an ID, b) include one more library, and c) write one line of JavaScript. Sweet.

As I said, you should check the web site for more details. One simple change you may want to make is an initial sort. That's as easy as:

$("#mydata").tablesorter({sortList:[[0,0]]})

You can add CSS to add pretty arrows to the headers, or keep it simple, as I did:

<style> th { cursor: pointer; } </style>

You can see a full demo of this here.

Raymond Camden's Picture

About Raymond Camden

Raymond is a developer advocate for Extend by Auth0. He focuses on serverless and enterprise cat demos. If you like this article, please consider visiting my Amazon Wishlist or donating via PayPal to show your support.

Lafayette, LA https://www.raymondcamden.com

Comments