<!--
The following code is from
Professional JavaScript for Web Developers
by Nicholas C. Zakas
ISBN: 978-0-7645-7908-0
April 2005
http://www.nczonline.net/
For purchase: http://www.amazon.com/Professional-JavaScript-Developers-Wrox-Guides/dp/0764579088
For publisher website: http://www.wrox.com/WileyCDA/WroxTitle/productCd-0764579088.html
-->
<html>
<head>
<title>Table Sort Example</title>
<script type="text/javascript">
function generateCompareTRs(iCol) {
return function compareTRs(oTR1, oTR2) {
var sValue1 = oTR1.cells[iCol].firstChild.nodeValue;
var sValue2 = oTR2.cells[iCol].firstChild.nodeValue;
return sValue1.localeCompare(sValue2);
};
}
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];
}
aTRs.sort(generateCompareTRs(iCol));
var oFragment = document.createDocumentFragment();
for (var i=0; i < aTRs.length; i++) {
oFragment.appendChild(aTRs[i]);
}
oTBody.appendChild(oFragment);
}
</script>
</head>
<body>
<P>Click on the table header to sort in ascending order.</p>
<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>
<tr>
<td>Smith</td>
<td>John</td>
</tr>
<tr>
<td>Johnson</td>
<td>Betty</td>
</tr>
<tr>
<td>Henderson</td>
<td>Nathan</td>
</tr>
<tr>
<td>Williams</td>
<td>James</td>
</tr>
<tr>
<td>Gilliam</td>
<td>Michael</td>
</tr>
<tr>
<td>Walker</td>
<td>Matthew</td>
</tr>
</tbody>
</table>
</body>
</html>
|