↑
Main Page
Sorting in descending order
<table border=”1” id=”tblSort”>
<thead>
<tr>
<th onclick=”sortTable(‘tblSort’, 0)”
style=”cursor:pointer”>Last Name</th>
<th onclick=”sortTable(‘tblSort’, 1)”
style=”cursor:pointer”>First Name</th>
</tr>
</thead>
<tbody>
<!-- data rows -->
</tbody>
</table>
Of course, this function isn’t limited to tables with just two columns. Any table with any number of
columns can take advantage of it, just so long as you remember to pass in the correct column index to
the function.
Sorting in descending order
In the first two examples, you learned how to sort single column and multicolumn tables in ascending
order. Now, it’s time to learn how to sort the table columns in descending order.
First and foremost, consider the expected behavior of a sortable table. When you sort a column in, say,
Microsoft Outlook, you click on the column header. When you do this, the column is sorted in ascending
order. If you then click on the column header a second time, the column sorts into descending order. This
functionality is pretty standard in user interface design, so you really want to mimic it in your tables.
You can already sort each column in ascending order, so you’re halfway there. The crux of this problem
is that, on the
second
click, you want to sort in descending order. This means that in order to sort in
descending order, you must already have clicked on the column header once (so the column is already
sorted in ascending order). You can simply reverse the order (using the
reverse()
method) of the col-
umn to sort in descending order.
To make this change, it’s necessary to once again modify the
sortTable()
function.
Modifying the sortTable() function
In order to create a descending sort, it is necessary to store the column index passed into the function for
later reference. To do this, you can create an
expando
property on the table. An expando property is an
extra JavaScript property that is added to an object during runtime. The expando property in this exam-
ple is called
sortCol
, and it simply stores the index of the column that was sorted last:
function sortTable(sTableID, iCol) {
var oTable = document.getElementById(sTableID);
var oTBody = oTable.tBodies[0];
var colDataRows = oTBody.rows;
var aTRs = new Array;
for (var i=0; i < colDataRows.length; i++) {
aTRs[i] = colDataRows[i];
}
376
Chapter 12
15_579088 ch12.qxd 3/28/05 11:40 AM Page 376
Free JavaScript Editor
Ajax Editor
©
→