![]() |
Web Development »
Client side scripting »
General
Beginner
License: The Code Project Open License (CPOL)
table sorting on client sideBy Rohith K Rajancustom client side javascript sorting - easy to customise |
Javascript, Windows, Visual Studio, Dev
|
||||||||||
|
Advanced Search |
|
|
|
||||||||||||||||
This tutorial contains client side sorting(ascending and descending) of a table according to the type of data you specify in the html .Add "type=Date" and "onclick="sortTable(event,0)"" attribute also to each cell in the thead section of table ( second parameter of the function is the index of the column starting from zero).
This javascipt code can be used to write your own sorting on any form of array datatype.As you know javascipt is a loosely typed langauage,so the generic sorting function available in the Array object can be used to sort any type of data in an array object.Only thing you have to do is to write a custom comparing logic which can be called with the Array.sort() function. With three easy steps you can implement your own sorting mechanism.
populate the array object with specific data you need.if table is to be sorted,take each row into the array.
Write the custom comparing function.if the values need to be sorted are of type date or float write a function to compare those values.
call the Array objects sort() function by passing the custom comparing function name as parameter.
The Array's sort function internally calls the function passed to it to compare two values.So this custom function should take two arguments.And it should return a positive or negative or a zero.if any other data it returns,this sort function will throw an error.In this example function Custom() is used to compare different type of data.So in this way you can implement sorting your own type of data.
Here's the code i have writen to implement sorting.
//what type of data to be sorted.
//need to mention in the table header cell tag.
var type;
//index of the column to be sorted.
var columnIndex,lastIndex,isDescending;
//varaiables for creating up arrow and down arrow.
var upArrow,downArrow;
function initSortArrows()
{
//create a span element.
upArrow = document.createElement("SPAN");
var node6 = document.createTextNode("6");
upArrow.appendChild(node6);
//apply css class to show '5' as an arrow.
upArrow.className = "arrow";
//creating span tag for downArrow.
downArrow = document.createElement("SPAN");
var node5 = document.createTextNode("5");
downArrow.appendChild(node5);
downArrow.className = "arrow";
}
function toString(value)
{
return value.toUpperCase();
}
function toDate(value)
{
return Date.parse(value);
}
function Custom(a,b)
{
if(a==undefined||b==undefined)
return 0;
var val1=a.children[columnIndex].innerText;
var val2=b.children[columnIndex].innerText;
var a1=val1.split('.');
var b1=val2.split('.');
//get the maximum length of array.
var maxlength;
if(a1.length>b1.length)
maxlength=a1.length;
else
maxlength=b1.length;
//iterate through array item to get individual order no .
for(var i=0;i<maxlength;i++)
{
//if both order number is same conitue to next order.else return the difference
if(a1[i]!=undefined && b1[i]!=undefined)
{
if(parseInt(a1[i])==parseInt(b1[i]))
{
continue;
}
else
{
if(parseInt(a1[i])<parseInt(b1[i]))
return isDescending?-1:+1;
if(parseInt(a1[i])>parseInt(b1[i]))
return isDescending ?+1:-1;
return 0;
}
}
//if one of the order does not exists,return 1 or -1.
else
{
if(a1[i]==undefined)
return -1;
else
return 1;
}
}
return 0;
}
//function returning another function.
function customCompare(type,isDescend,columnIndex)
{
var TypeCast;
//assign the typecast to point to the cast function.
//if type is 'Custom' then return the Custom() function.
if(type=="Number")
TypeCast=Number;
else if(type=="Date")
TypeCast=toDate;
else if(type=="Custom")
return Custom;
else
TypeCast=toString;
return function(row1,row2)
{
var val1,val2;
val1=row1.children[columnIndex].innerText;
val2=row2.children[columnIndex].innerText;
if(TypeCast(val1)<TypeCast(val2))
return isDescend ?-1:+1;
if(TypeCast(val1)>TypeCast(val2))
return isDescend ?+1:-1;
return 0;
}
}
//function used for sorting table rows.
function sortTable(eventclick,index)
{
//if arrows are not created create it.
if(upArrow==undefined)
initSortArrows();
//get the TD element.
var cell=eventclick.srcElement;
//if the user clicks on the "SPAN" tag which was added dynamically.
if(cell.tagName=="SPAN")
cell=cell.parentElement;
else if (cell.type==undefined)
type="String";
else
type=cell.type;
//set the current index.
columnIndex=index;
//get the head tag.
var thead=cell.parentElement;
var table=thead.parentElement.parentElement;
//if clicked on span tag go one level up.
if(!table.tBodies)
{
table=table.parentElement;
thead=thead.parentElement;
}
var tblBody = table.tBodies[0];
var tblRows = tblBody.rows;
//set the direction.
if(columnIndex==lastIndex)
{
if(isDescending==true)
isDescending=false;
else
isDescending=true;
}
else
isDescending=true;
//make the array of rows.
var rowArray=new Array();
//add each row to array.
for(var i=0;i<tblRows.length;i++)
{
rowArray[i]=tblRows[i];
}
//call the generic function to sort the array.
//custom comare will return another function whih compares the value passed.
rowArray.sort(customCompare(type,isDescending,columnIndex));
//append the sorted array to table.
for(var i=0;i<rowArray.length;i++)
{
tblBody.appendChild(rowArray[i]);
}
//first time sorting.
if(lastIndex==undefined)
{
cell.appendChild(downArrow.cloneNode(true));
isDescending=true;
}
else if(index!=lastIndex)
{
thead.cells[lastIndex].removeChild(thead.cells[lastIndex].children[0]);
cell.appendChild(downArrow.cloneNode(true));
}
else if(index==lastIndex)
{
cell.removeChild(cell.children[0]);
if(isDescending==true)
cell.appendChild(downArrow.cloneNode(true));
else
cell.appendChild(upArrow.cloneNode(true));
}
//set the last sorted column index.
lastIndex=index;
}
The rowArray.sort() function will call customCompare() function internally for each time to compare two values.This function returns another function which will take two arguments and return +1,-1 or 0..Only thing we have to take care is return a positive or negative data from customCompare function.Here i have added one more level of abstraction,which will find out what type of data to compare,which is specified as a 'type' attribute html table header columns
18 Sept 2007 -created..
05 oct 2007 -Modified
16 Oct 2007-Modified
| You must Sign In to use this message board. | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
General
News
Question
Answer
Joke
Rant
Admin
|
PermaLink |
Privacy |
Terms of Use
Last Updated: 19 Mar 2008 Editor: |
Copyright 2007 by Rohith K Rajan Everything else Copyright © CodeProject, 1999-2009 Web12 | Advertise on the Code Project |