The JQuery library that allows this to happen is called Tablesorter. Tablesorter has a ton of very useful features, including having a very small code base, the ability to sort across multiple columns and is compatible with just about every web-browser that’s currently being used, even IE 6. It has sort parsers for a number of types of formats, including text, URIs, integers, currency, floats, IP addresses and dates, so whatever type of data you have in the table, chances are it will be able to intelligently sort it.
Here’s how to create a sortable table with TableSorter and JQuery
(1) Get the required libraries and reference them.
You’ll want to download the minfiied version of Tablesorter from the Tablesorter website. The slimmed-down version comes in at 12 KB. You can download that here. You’ll also want to get a copy of the latest version of JQuery which is available form the JQuery Website. Once you get those two files downloaded, you’ll want to add references to them in your page’s <HEAD>. They should look something like this depending on where you placed your files:
(2) Make an HTML Table
Here’s a demonstration table that the Tablesorter website provides for us to use. Simply add this to the body of your page:
<table id="myTable"> <thead> <tr> <th>Last Name</th> <th>First Name</th> <th>Email</th> <th>Due</th> <th>Web Site</th> </tr> </thead> <tbody> <tr> <td>Smith</td> <td>John</td> <td>email@example.com</td> <td>$50.00</td> <td>http://www.jsmith.com</td> </tr> <tr> <td>Bach</td> <td>Frank</td> <td>firstname.lastname@example.org</td> <td>$50.00</td> <td>http://www.frank.com</td> </tr> <tr> <td>Doe</td> <td>Jason</td> <td>email@example.com</td> <td>$100.00</td> <td>http://www.jdoe.com</td> </tr> <tr> <td>Conway</td> <td>Tim</td> <td>firstname.lastname@example.org</td> <td>$50.00</td> <td>http://www.timconway.com</td> </tr> </tbody> </table>
(3) Sort Your Table
The only thing left to do to make our quick and dirty demo of the table sorter to work is to call the sorting library using the document.ready() function that’s frequently used with JQuery. That will look something like this:
(4) Further Development
The next logical step is to add some CSS formatting that will give the user a better idea of which sort direction they’re doing. You can see a demo of how to style the different sort directions on the Tablesorter website, which would be a must on any production site. You might also want to play around with doing multi-column sorts and with their widget system.