PDA

View Full Version : Dynamic table sort in client side script


loupgarou
03-31-2001, 08:07 AM
Is there anyway to sort a table dynamically in the client?

I have the server generating a html table but the data is not sorted. can I get the output sorted when the client views it?

Dr. Web
03-31-2001, 08:39 PM
I might suggest using arrays for the data. Then you could have JS or XML do the sort for you, and fill up then table.

kdjoergensen
04-11-2001, 01:16 PM
In microsoft internet exploder and Netscape 6 you can sort the table. My suggestion is along these lines:

On this page I have an example of how you can loop through a table:
http://imaginethat.htmlplanet.com/table/create6.html

In my example above I assign some eventhandlers to each TD cell. Instead you could create an Array and register the info as you go along, sort it, and then write it back:

var myTable = (document.all) ? document.all["tableID"] : document.getElementById('tableID');
var masterAry = new Array();

if (document.all){ //internet explorer
for (var i=0;i<myTable.rows.length;i++){
for (var j=0;j<myTable.rows[i].cells.length;j++){
var cellObj = myTable.rows[i].cells[j];
masterAry[masterAry.length] = cellObj.innerText
}
}
} else if (document.getElementById){ // NS6
var TRColl = myTable.getElementsByTagName('TR');
for (var i=0; i<TRColl.length;i++){
var TDColl = TRColl[i].getElementsByTagName('TD');
for (var j=0; j<TDColl.length;j++){
var cellObj = TDcoll[j];
masterAry[masterAry.length] = cellObj.childNodes[0];
}
}
}

An Array can be sorted using the .sort() method. Sorting will be done according to ASCII characters (call it alphabetically).

masterAry.sort();

Finally you will need to write back to the cells again:

var c = 0;
if (document.all){ //internet explorer
for (var i=0;i<myTable.rows.length;i++){
for (var j=0;j<myTable.rows[i].cells.length;j++){
myTable.rows[i].cells[j].innerText = masterAry[c++];
}
}
} else if (document.getElementById){ // NS6
var TRColl = myTable.getElementsByTagName('TR');
for (var i=0; i<TRColl.length;i++){
var TDColl = TRColl[i].getElementsByTagName('TD');
for (var j=0; j<TDColl.length;j++){
TRColl[i].TDcoll[j].appendChild(masterAry[c++]);
}
}
}

A few notes: it does not work for Netscape 4.
You can only have ONE (1) text node inside the tables (with the script above.. otherwise must be modified). e.g. you can have:
<td>here is some text</td>
but not:
<td>here is <b>bold</b> text</td>

Hope you can use it..
Kenneth
http://imaginethat.htmlplanet.com/