If you’re publishing any sort of complex statistics, it’s often helpful to be able to sort this data. If the data is coming from a database, you can often do this sorting on the server side rather easily, but sorting on the browser side in JavaScript is generally a better user experience. Contrary to what the “table vs. CSS” rhetoric implies, tabular data still belongs in tables (though layout does not). And HTML tables offer a standard formatting for sortable data, allowing us to apply the same JavaScript behaviors to a wide variety to data.
Enter sorttable, a JavaScript from Stuart Langridge. Sorttable automatically adds sorting behavior to any table explicitly classified as sortable, with the simple semantic HTML: class="sortable". This is a great demonstration of the benefits of separating form from function. Unfortunately, anyone using sorttable with descriptive table markup in HTML will quickly run into a problem: totals and averages get sorted along with everything else.
Let’s say you have a table of people with names, ages, and number of children. Sorttable lets you sort this list by name, age, or number of children. But at the bottom of this table, you have an average age and total children. Sorttable sorts this as well. What to do? One solution is to take advantage of the rarely-used tfoot HTML element. By wrapping totals and averages in a tfoot, our HTML can indicate that this content is distinct from the rest of the table. Problem: solved! Semantic HTML saves the day again.
Well, not exactly. We still need to make sorttable take note of this distinction. To do that, we just need to change this:
for (j=1;j<table.rows.length;j++) { newRows[j-1] = table.rows[j]; }
to this:
for (j=1;j<table.rows.length;j++) {
if ( table.rows[j].parentNode.tagName.toLowerCase() != 'tfoot' )
newRows[j-1] = table.rows[j];
}
This should appear around line 78 in sorttable.js. What this does is exclude any table rows within a tfoot from sorting. Now we can safely apply sorttable to any HTML table we want to sort, even if it has non-sortable information at the bottom.
Update: The original sorttable.js has been updated to include tfoot checking, so there’s no longer any need to edit the script.