Client-side Table Sorting Using Javascript

What about the idea of giving the user power of sorting the table's column using JavaScript. User can sort any column of the table.
I saw this facility from a software I was using. It was running very fast and smoothly. That web app was using JavaScript from another site. So I though it will be a good idea checking this JavaScript code. I checked and posted it here.
I have mentioned a link to the original source also.

JavaScript Table- Sorting Working Example:

Position Jun 07Position Jun 06Porg. Language

More Ranks

Javascript Table Sorting Code:

<script type="text/javascript">
var sortedOn = 0;
function SortTable(sortOn) {
var table = document.getElementById('results');
var tbody = table.getElementsByTagName('tbody')[0];
var rows = tbody.getElementsByTagName('tr');
var rowArray = new Array();
for (var i=0, length=rows.length; i<length; i++) {
rowArray[i] = new Object;
rowArray[i].oldIndex = i;
rowArray[i].value = rows[i].getElementsByTagName('td')[sortOn].firstChild.nodeValue;
if (sortOn == sortedOn) { rowArray.reverse(); }
else {
sortedOn = sortOn;
Decide which function to use from the three:RowCompareNumbers,
RowCompareDollars or RowCompare (default).
For first column, I needed numeric comparison.
if (sortedOn == 0) {
else {
var newTbody = document.createElement('tbody');
for (var i=0, length=rowArray.length ; i<length; i++) {
table.replaceChild(newTbody, tbody);
function RowCompare(a, b) {
var aVal = a.value;
var bVal = b.value;
return (aVal == bVal ? 0 : (aVal > bVal ? 1 : -1));
// Compare number
function RowCompareNumbers(a, b) {
var aVal = parseInt( a.value);
var bVal = parseInt(b.value);
return (aVal - bVal);
// compare currency
function RowCompareDollars(a, b) {
var aVal = parseFloat(a.value.substr(1));
var bVal = parseFloat(b.value.substr(1));
return (aVal - bVal);

HTML Code:
Here is the html code I have used in table sorting example.

This script does not use server-side script, so no page refresh for sorting data in ascending or descending order. It also maintain row data while sorting column.

You may have find this table sorting script very cool! Digg it?
Reference: Table Sorting by Porter Glendinning

  • # 1 - by Hendry Agung

    i'm new to blog,i want to use this script, how to put this script in bloger post ?

Comment pages
1 2 222
Comments are open for an year period. Please, write here on Facebook page.