Sorting table rows according to table header column using javascript or jquery

html, html-table, javascript, jquery

Solution

You might want to see this page: http://blog.niklasottosson.com/?p=1914

I guess you can go something like this:

DEMO:http://jsfiddle.net/g9eL6768/2/

HTML:

 <table id="mytable"><thead>
  <tr>
     <th id="sl">S.L.</th>
     <th id="nm">name</th>
  </tr>
   ....

JS:

//  sortTable(f,n)
//  f : 1 ascending order, -1 descending order
//  n : n-th child(<td>) of <tr>
function sortTable(f,n){
    var rows = $('#mytable tbody  tr').get();

    rows.sort(function(a, b) {

        var A = getVal(a);
        var B = getVal(b);

        if(A < B) {
            return -1*f;
        }
        if(A > B) {
            return 1*f;
        }
        return 0;
    });

    function getVal(elm){
        var v = $(elm).children('td').eq(n).text().toUpperCase();
        if($.isNumeric(v)){
            v = parseInt(v,10);
        }
        return v;
    }

    $.each(rows, function(index, row) {
        $('#mytable').children('tbody').append(row);
    });
}
var f_sl = 1; // flag to toggle the sorting order
var f_nm = 1; // flag to toggle the sorting order
$("#sl").click(function(){
    f_sl *= -1; // toggle the sorting order
    var n = $(this).prevAll().length;
    sortTable(f_sl,n);
});
$("#nm").click(function(){
    f_nm *= -1; // toggle the sorting order
    var n = $(this).prevAll().length;
    sortTable(f_nm,n);
});

Hope this helps.

Problem

I have something like this ``` <table> <thead> <tr> <th>S.L.</th> <th>name</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>Ronaldo</td> </tr> <tr> <td>2</td> <td>Messi</td> </tr> <tr> <td>3</td> <td>Ribery</td> </tr> <tr> <td>4</td> <td>Bale</td> </tr> </tbody> </table> ``` What i want is to sort the `<tr>` of `<tbody>` when clicked `th` in ascending and descending order alternatively in according to the following `th` clicked. - so if some one clicks the `S.L` `th` then it shows the table rows in descending and then ascending order alternatively at every click. - When clicked `Name` `th` it should show the names in descending order and then ascending order without change in their respective `S.L` here is fiddle

Original source

Related problems