If I have the following:
<table>
<thead>
<tr>
<th><a href="Index.cfm?Sort=0">First</a></th>
<th><a href="Index.cfm?Sort=1">Second</a></th>
<th><a href="Index.cfm?Sort=2">Third</a></th>
</tr>
</thead>
<tbody>
<tr>
<td>A</td>
<td class="num">123</td>
<td><input name="XYZ"></td>
</tr>
</tbody>
</table>
Q: How do I sort the table body based upon which table header cell was clicked?
<script>
$('th a').click(function() {
var $this = $(this).closest('th');
console.log($this.index());
return false;
});
</script>
(I made each of the table header cells hyperlinks so that if the user has JavaScript turned off, it will follow the link and be sorted on the server side).
function OrderBy(a,b,n) {
if (n) return a-b;
if (a < b) return -1;
if (a > b) return 1;
return 0;
}
$('th a').click(function() {
var $th = $(this).closest('th');
$th.toggleClass('selected');
var isSelected = $th.hasClass('selected');
var isInput= $th.hasClass('input');
var column = $th.index();
var $table = $th.closest('table');
var isNum= $table.find('tbody > tr').children('td').eq(column).hasClass('num');
var rows = $table.find('tbody > tr').get();
rows.sort(function(rowA,rowB) {
if (isInput) {
var keyA = $(rowA).children('td').eq(column).children('input').val().toUpperCase();
var keyB = $(rowB).children('td').eq(column).children('input').val().toUpperCase();
} else {
var keyA = $(rowA).children('td').eq(column).text().toUpperCase();
var keyB = $(rowB).children('td').eq(column).text().toUpperCase();
}
if (isSelected) return OrderBy(keyA,keyB,isNum);
return OrderBy(keyB,keyA,isNum);
});
$.each(rows, function(index,row) {
$table.children('tbody').append(row);
});
return false;
});
You might be interested in jQuery Plugin: Tablesorter or any any other table sort plugin.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With