Main Page

JavaScript code

Using this methodology, the comparison function returns the correct value no matter which data type is
being used.
Next, you modify the
function to use the new comparison function generator. To do so,
this function also must accept an additional argument indicating the data type to use for the compari-
son. Then, this data type must be passed into the
function sortTable(sTableID, iCol, sDataType) {
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, sDataType));
var oFragment = document.createDocumentFragment();
for (var i=0; i < aTRs.length; i++) {
oTable.sortCol = iCol;
With the JavaScript code all done, it’s time to add extra data to the table for the various data types:
<table border=”1” id=”tblSort”>
<th onclick=”sortTable(‘tblSort’, 0)”
style=”cursor:pointer”>Last Name</th>
<th onclick=”sortTable(‘tblSort’, 1)”
style=”cursor:pointer”>First Name</th>
<th onclick=”sortTable(‘tblSort’, 2, ‘date’)”
<th onclick=”sortTable(‘tblSort’, 3, ‘int’)”
It’s important not to use the equality operator (
) in this case. Although it works for
strings and numbers (both integer and float), it won’t work for dates. Remember,
dates are objects, not primitive values. This means that the equality operator com-
pares the objects to see if they are the same; it does not compare the values of the
objects. However, the less-than and greater-than symbols use the
method of the
objects to compare their milliseconds representation.
Chapter 12
15_579088 ch12.qxd 3/28/05 11:40 AM Page 380

JavaScript EditorFree JavaScript Editor     Ajax Editor