Created
April 7, 2016 15:26
-
-
Save mangeshpawar/85c52e8ff268024f34f1156be31ca253 to your computer and use it in GitHub Desktop.
Sort column wise table rows
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
<!DOCTYPE html> | |
<html> | |
<head> | |
<title></title> | |
<script src="https://code.jquery.com/jquery-1.12.0.min.js"></script> | |
<script src="https://code.jquery.com/jquery-migrate-1.2.1.min.js"></script> | |
</head> | |
<body> | |
<style> | |
td { | |
width: 10em; | |
} | |
th{ | |
cursor:hand; | |
cursor:point; | |
} | |
</style> | |
<table class="table-sorter"> | |
<tr> | |
<th class="sortable">One</th> | |
<th>Two</th> | |
<th class="sortable"> Three</th> | |
</tr> | |
<tr> | |
<td> <input name="a" value=""/> </td> | |
<td>1lb</td> | |
<td>Z</td> | |
</tr> | |
<tr> | |
<td><input name="a" value=""/></td> | |
<td>3lb</td> | |
<td>A</td> | |
</tr> | |
<tr> | |
<td><input name="a" value=""/></td> | |
<td>5lb</td> | |
<td>K</td> | |
</tr> | |
<tr> | |
<td><input name="a" value=""/></td> | |
<td>25lb</td> | |
<td>Y</td> | |
</tr> | |
</table> | |
<script type="text/javascript"> | |
var ts = ts || {}; | |
var sortStatus = {}; | |
ts.getValue = function(tdElem){ | |
var inputElemLst = $(tdElem).find("input:first"); | |
return inputElemLst.length ? inputElemLst.val() : $(tdElem).text(); | |
}; | |
ts.handleSortClick = function(event){ | |
var columnIndex = $(this).index() + 1; | |
$('table.table-sorter tr td:nth-child(' + columnIndex + ')').css("color", "#F00"); | |
var tdList = $('table.table-sorter tr td:nth-child(' + columnIndex + ')'); | |
for(var index=0;index<tdList.length;++index){ | |
tdList[index].sortValue = ts.getValue(tdList[index]); | |
} | |
if(sortStatus[columnIndex] == 1){ | |
tdList.sort(function(tdA,tdB){ | |
return tdA.sortValue < tdB.sortValue; | |
}); | |
sortStatus[columnIndex] = 0; | |
} else { | |
tdList.sort(function(tdA,tdB){ | |
return tdA.sortValue > tdB.sortValue; | |
}); | |
sortStatus[columnIndex] = 1; | |
} | |
var finalSortedRows = []; | |
console.log('sorted tdList',tdList); | |
for(var index=0;index<tdList.length;++index){ | |
finalSortedRows.push( $( tdList[index] ).closest("tr")[0] ); | |
} | |
console.log('finalSortedRows',finalSortedRows); | |
//$("table.table-sorter tr").remove(); | |
//$(finalSortedRows).appendTo; | |
$("table.table-sorter").append(finalSortedRows); | |
$(this).css("color", "#F00"); | |
}; | |
$("body").on("click","table.table-sorter th.sortable",ts.handleSortClick); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment