Javascript – sort tables (by column values) [easy and opensource]
If you see a table in a client-side application, you’ll expect to be able to click on the headers and have the table sort, would you not? I know it always annoys me when you can’t. A fair few web applications do allow this; most of them, which are pulling this data by submitting a SQL query to a relational database (an environment eminently suited to tabular data) implement this by resubmitting the whole page with something like ordercolumn=4 in the URL, and then adding an ORDER BY clause to their SQL query to return the data from the DB ordered by the specified column.
Resubmit the page? Just to sort data we already have? I’m sure we can do better than that: just using javascript!
Take a look at sorrtable javascript library and follow the simple steps to have a sortable table.
1. Download the Javascript library
2. Include the Javascript library, by putting a link to it in the HEAD of your page, like so:
<script src="sorttable.js"></script>
3. Mark your table as a sortable one by giving it a class of “sortable”:
<table class="sortable">
Note that the library’s JavaScript file is called sorttable (two Ts), but the class you add to the table is sortable (one T).
Easy, isn’t it?
Related posts: