Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting a table based on which header cell was clicked

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).

like image 785
Phillip Senn Avatar asked Dec 03 '22 12:12

Phillip Senn


2 Answers

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;
});
like image 136
Phillip Senn Avatar answered Dec 26 '22 05:12

Phillip Senn


You might be interested in jQuery Plugin: Tablesorter or any any other table sort plugin.

like image 21
Crozin Avatar answered Dec 26 '22 05:12

Crozin