topical media & game development

talk show tell print

professional-javascript-12-TableSortExample4.htm / htm

          <title>Table Sort Example</title>
          <script type="text/javascript">
              function convert(sValue, sDataType) {
                  switch(sDataType) {
                      case "int":
                          return parseInt(sValue);
                      case "float":
                          return parseFloat(sValue);
                      case "date":
                          return new Date(Date.parse(sValue));
                          return sValue.toString();
              function generateCompareTRs(iCol, sDataType) {
                  return  function compareTRs(oTR1, oTR2) {
                              var vValue1 = convert(oTR1.cells[iCol].firstChild.nodeValue, sDataType);
                              var vValue2 = convert(oTR2.cells[iCol].firstChild.nodeValue, sDataType);
                              if (vValue1 < vValue2) {
                                  return -1;
                              } else if (vValue1 > vValue2) {
                                  return 1;
                              } else {
                                  return 0;
              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];
                  if (oTable.sortCol == iCol) {
                  } else {
                      aTRs.sort(generateCompareTRs(iCol, sDataType));
                  var oFragment = document.createDocumentFragment();
                  for (var i=0; i < aTRs.length; i++) {
                  oTable.sortCol = iCol;
          <p>Click on the table header to sort in ascending order.</p>
          <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')" 

(C) Æliens 20/2/2008

You may not copy or print any of this material without explicit permission of the author or the publisher. In case of other copyright issues, contact the author.