Tuesday, April 26, 2011

Sort Table 1

Here i have given the sample code of how Sort table works


<html>
<head>
<script>

function compareTRs(oTR1, oTR2)
{
var sValue1 = oTR1.cells[0].firstChild.nodeValue;
var sValue2 = oTR2.cells[0].firstChild.nodeValue;

return sValue2.localeCompare(sValue1);
}

function sortTable(sTableID)
{
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(compareTRs);

var oFragment = document.createDocumentFragment();

for(var i=0; i < aTRs.length; i++)
{
oFragment.appendChild(aTRs[i]);
}

oTBody.appendChild(oFragment);

}
</script>




</head>






<table border="1" id="tblSort">
<thead>
<tr>
<th onclick="sortTable('tblSort');" style='cursor:pointer;'> Last Name</th>
</tr>
</thead>

<body>
<tr>
<tdA> Smith</td>
</tr>
<tr>
<tdB> Johnson</td>
</tr>
<tr>
<td> C Henderson</td>
< /tr>
<tr>
<td> DWilliams </td>
</tr>
< tr>
<tdE> E Gilliam </td>
< /tr>
<tr>
<td>F Walker </td>
</tr>
<tr>
<td>Z </td>
</tr>
</tbody>
</table>
</html>

How it works


Sorting is done by getting the values of the column [dom collections] from the table and storing it to an array then sorting the array values.

Now the tr values are sorted and stored in a array ,

Here the sorted values needs to be appended in the table by replacing old tr,

That is done by creating document fragment and adding all the elements (array values) to it

Then appending all child nodes of document fragment back in to the tbody element

ps: source: Wrox Professional JavaScriptTM for Web Developers

No comments: