Thursday, April 14, 2005

sortable table with HTML and javascript

Is table should be sortable? Yes, of course.

I had a boring and frustrated afternoon, to kill my time, I wrote some code to do this.

<html>
<head>
<script>
function initiateTableSort(){
 var vTables = document.getElementsByTagName("table");
 var i;
 for( i in vTables ){
  var vFirstRow = vTables[ i ].rows[ 0 ];
  var j;
  for( j in vFirstRow.cells ){
   vFirstRow.cells[ j ].onclick=doTableSort;
   vFirstRow.cells[ j ].ondblclick=doTableSort;
  }
 }
}

var iTeBeCompared = 0;
function doTableSort( e ){
 var vTargetTable = e.target;
 while( vTargetTable.nodeName != "TABLE"  ) vTargetTable = vTargetTable.parentNode;
 var vTR = vTargetTable.rows[ 0 ];
 var i = e.target.cellIndex;
 var j;
 iToBeCompared = i;
 var vTRs = new Array();
 for( i = 1; i < vTargetTable.rows.length; i ++ ){
  var vRowData = new Array();
  var cells = vTargetTable.rows[ i ].cells;
  for( j = 0; j < cells.length; j++ ){vRowData[ j ] = cells[ j ].innerHTML;}
  vTRs[ i - 1 ] = vRowData;
 }
 if( e.type=="click") vTRs.sort( sortRoutineDes );
 else vTRs.sort( sortRoutineAs );
 for( i = 0 ; i < vTRs.length; i ++ ){
  for(j = 0 ; j < vTRs[ 0 ].length; j ++ ) 
   vTargetTable.rows[ i + 1 ].cells[ j ].innerHTML = vTRs[ i ][ j ];
 }

}

function sortRoutineDes( a, b ){
 return (a[iToBeCompared] > b[iToBeCompared])? -1:1;
}

function sortRoutineAs( a, b ){
 return (a[iToBeCompared] < b[iToBeCompared])? -1:1;
}

</script>
</head>
<body onload="initiateTableSort()">
<table border= "1">
 <tr>
  <th>a</th><th>b</th><th>c</th>
 </tr>
 <tr>
  <td>x1</td><td>3</td><td>1</td>
 </tr>
 <tr>
  <td>a2</td><td>2</td><td>2</td>
 </tr>
 <tr>
  <td>a3</td><td>4</td><td>3</td>
 </tr>
<tr>
  <td>a3</td><td>1</td><td>3</td>
 </tr>
<tr>
  <td>a3</td><td>7</td><td>3</td>
 </tr>
<tr>
  <td>a3</td><td>8</td><td>3</td>
 </tr>
<tr>
  <td>a3</td><td>0</td><td>3</td>
 </tr>
<tr>
  <td>a3</td><td>9</td><td>3</td>
 </tr>

</table>
</body>
</html>

Labels: ,

2 Comments:

Anonymous Anonymous said...

This comment has been removed by a blog administrator.

12:10 AM  
Anonymous Anonymous said...

This comment has been removed by a blog administrator.

9:44 AM  

Post a Comment

<< Home