Categories
DHTML JavaScript

Sortable Tables with JavaScript

For years I've fiddled with trying to make my tables sort in JavaScript.  The user can simply click on the column header to make the table sort on that column.  Click again and it sorts the other way.

There were various scripts out there to do it, but I never had the time and need all at once to get one to work.  None seemed to really work well, or they weren't documented well.

Now I've found it. This one works right out of the box. It's well documented on the page, but here's the gist of it;

To make the Javascript available to your pages:

  • Load the sortabletable.js file into your site.
  • Reference the script in the <head> section of your pages.

Now make the following modifications to the pages with tables;

  • Wrap the row that contains your column headers with <thead></thead> tags.
  • Make sure the row with the colum headers used <th></th> tags instead of <td></td>.
  • Wrap the rows that contain your table data with <tbody></tbody> tags.
  • Add an id="MyTable" attribute to the <table> tag for each table you want sorted.  Of course, the id must be unique on the page.
  • Place the sortable table object immediately after each sortable table.  It's shown in the sample code on the site, easy to place with a simple cut and paste, but remember to replace the 'MyTable' string with the id you used in that table's <table> tag.

That's it!  The table now sorts.  Sweet.

Here's where to find it:

While you're there, remember how whoever runs that site pays his or her bills.

If you're not familiar with the very helpful but little used <th><thead><tbody> and <tfoot> tags, Google them.

2009-04-04: Late News: There's a more advanced table sorting method in this frequency-decoder.com article.

2009-08-10: Late News: And now this great script at yoast.com that has alternate row colouring in the javascript, so that it sorts properly.