This article will describe a javascript which will make any <table> sortable on all columns.
Update: Thanks to a comment to this post, I corrected a problem with Firefox. I am now using textContext for non-IE browsers as it’s more widely supported.
Update 2: I’ve written a follow up to this article adding additional functionality not mentioned in this article.
Source: sortableTable.js
Example: Example
Here is an example (the above link will be better for looking at the HTML source):
| Name | Age | Phone | |
|---|---|---|---|
| Jon Doe | 21 | jon@doe.com | 111-111-1111 |
| Joe Bob | 20 | joe@bob.com | 222-222-2222 |
| Fake Guy | 25 | fake@guy.com | 555-555-5555 |
With the javascript included, the table needs to have class sortableTable, exactly one <thead> with exactly one row, and exactly one <tbody>.
To make a particular column the default sorted column (it’s be sorted upon the initial page load), add the class defaultSort to the particular <th> in the one row in <thead>.
The javascript also automatically adds the classes even and odd to the even and odd numbered rows for ease of styling.
The sorting is done based off of the innerTexttextContent of each cell, so if the cell contains HTML and you are expecting it to sort in that way, it may be sorted differently. For example, if one cell had <a href="federmanscripts.com">Z</a> and another had <b>A</b>, the cell containing “Z” would be before the one containing “A” if innerTexttextContent was used, but with innerTexttextContent the “A” would come first, as expected by the user. In short, the displayed text in the cell is what the column is sorted by.
