Search code examples
jqueryjquery-mobiletablesortertablerowsorter

Sort table by second column :jquery


I seen this example from another question, it uses plain javascript to sort a table by the first column, does anyone know how i would sort by the second column?.

Im on a mobile device at the moment so I cant post code, a js fiddle is in the comments showing the example.


Solution

  • This is a very simple sorting script, so take it as that (demo)

    function sortTable(column, direction){
        column = column || 0;
        var tbl = document.getElementById("caltbl").tBodies[0];
        var store = [];
        for(var i=0, len=tbl.rows.length; i<len; i++){
            var row = tbl.rows[i];
            var sortnr = row.cells[column].textContent || row.cells[column].innerText;
            if (!isNaN(sortnr)) { sortnr = parseFloat(sortnr); }
            store.push([sortnr, row]);
        }
        store.sort(function(x,y){
            return x[0] > y[0] ? 1 : x[0] < y[0] ? -1 : 0;
        });
        // look for "d" (descending) in the direction to switch sort direction
        if (direction && /d/.test(direction)) { store.reverse(); }
        for(var i=0, len=store.length; i<len; i++){
            tbl.appendChild(store[i][1]);
        }
        store = null;
    }