Sorting a Table with the Javascript Prototype Library
| Number |
String |
Date |
| 2 |
Sometimes |
08/30/1999 |
| 0 |
I |
12/21/2022 |
| 1 |
Eat |
01/01/1111 |
| 01 |
Many |
11/05/1755 |
| 22 |
Plump |
06/16/1981 |
| -3 |
Pigs. |
03/22/2006 |
The example uses Javascript to sort the rows of the table. Click the column headers to see the sorting in action. The Javascript I've written uses the Prototype Javascript library (1.5.0_pre1) that introduced the ability to use CSS selectors to target DOM elements.
I'm also using the Enumerable.sortBy() method to perform the logic of sorting the rows. sortBy() is easy to use because you only need to feed it the string or number you want compared, and it'll do the rest. Take a look at the Javascript.
Notes
- No inline Javascript or CSS!
- Besides a properly formed table, the only change to the HTML markup is the addition of a "genericTable" class. The class is used in the Javascript to attach the functions. The class could easily be renamed, or changed into an id. However, if changed to an id, I wouldn't be able to have multiple instance of the genericTable.
- This does not work in IE. I believe this version of Prototype has some weird memory leak bugs in IE.
- The "Date" column is treated as if it were a string. That's why it's not being sorted correctly. The Javascript I've written does not attempt to identify dates and sort accordingly.