Last active
December 23, 2015 02:29
-
-
Save frayhan32/6567300 to your computer and use it in GitHub Desktop.
SORTTABLE FOR JS
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Copyright 2013 FARIS RAYHAN adapted from WROX.com | |
//No warranty given . Free distributed are encouraged | |
//Below the sorttable function i usuallay used in my work | |
//applied exactly on thead of table on event click | |
//Generally we have 3 associatied function here | |
/=====================================================/ | |
/1.===============CONVERT FUNCTION ====================/ | |
/=====================================================/ | |
//Build convert function to detect the datatype of each column | |
//must be build to assure success work | |
function convert(value,dataType){ | |
switch(dataType){ | |
case'int': | |
return parseInt(value); | |
case'float': | |
return parseFloat(value); | |
case'date': | |
return new Date(Date.parse(value)); | |
return value.toString(); | |
} | |
} | |
/=====================================================/ | |
/2.===============GENERATE COMPARE ====================/ | |
/=====================================================/ | |
function generateCompare(iCol,dataType){ | |
return function compare(oTr1,oTr2){ | |
var vValue1,vValue2; | |
if(oTr1.cells[iCol].getAttribute("value")){ | |
vValue1=convert(oTr1.cells[iCol].getAttribute("value"),dataType) | |
vValue2=convert(oTr2.cells[iCol].getAttribute("value"),dataType) | |
}else{ | |
vValue1=convert(oTr1.cells[iCol].firstChild.nodeValue,dataType) | |
vValue2=convert(oTr2.cells[iCol].firstChild.nodeValue,dataType) | |
} | |
if(vValue1<vValue2){ | |
return -1; | |
}else if(vValue1>vValue2){ | |
return 1; | |
}else{ | |
return 0; | |
} | |
} | |
function sortTable(sTableID, iCol, sDataType) { | |
var oTable = document.getElementById(sTableID); //get table reference | |
var oTBody = oTable.tBodies[0]; //get first Tbody in related table | |
var colDataRows = oTBody.rows; //get first all row in related table | |
var aTRs = new Array; //create a array variable for temporary container | |
for (var i=0; i < colDataRows.length; i++) { | |
aTRs[i] = colDataRows[i]; //loop them and store to atr | |
} | |
if(oTable.sortCol==iCol){ | |
aTRs.reverse(); | |
}else{ | |
aTRs.sort(generateCompareTRs(iCol, sDataType)); | |
} | |
var oFragment = document.createDocumentFragment(); | |
for (var i=0; i < aTRs.length; i++) { | |
oFragment.appendChild(aTRs[i]); | |
} | |
oTBody.appendChild(oFragment); | |
oTable.sortCol=iCol; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment