Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery sorting a table without the plugin

Is there a jquery function to sort a table. I am aware of the JQuery Tablesorter plugin but I want to avoid using it if possible.

As a FYI - The table that I have a header with custom images to indicate ascending and descending. The data type could be pretty much any type.

EDIT:Can I do sorting of a table in Javascript?

like image 602
DotnetDude Avatar asked Dec 09 '22 21:12

DotnetDude


1 Answers

It is very much possible. You can do it like this

function sortTable(table, col, reverse) {
    var tb = table.tBodies[0], // use `<tbody>` to ignore `<thead>` and `<tfoot>` rows
        tr = Array.prototype.slice.call(tb.rows, 0), // put rows into array
        i;
    reverse = -((+reverse) || -1);
    tr = tr.sort(function (a, b) { // sort rows
        return reverse // `-1 *` if want opposite order
            * (a.cells[col].textContent.trim() // using `.textContent.trim()` for test
                .localeCompare(b.cells[col].textContent.trim())
               );
    });
    for(i = 0; i < tr.length; ++i) tb.appendChild(tr[i]); // append each row in order
}

function makeSortable(table) {
    var th = table.tHead, i;
    th && (th = th.rows[0]) && (th = th.cells);
    if (th) i = th.length;
    else return; // if no `<thead>` then do nothing
    while (--i >= 0) (function (i) {
        var dir = 1;
        th[i].addEventListener('click', function () {sortTable(table, i, (dir = 1 - dir))});
    }(i));
}

function makeAllSortable(parent) {
    parent = parent || document.body;
    var t = parent.getElementsByTagName('table'), i = t.length;
    while (--i >= 0) makeSortable(t[i]);
}

window.onload = function () {makeAllSortable();};

Take a look at this Fiddle

(I am not the author of code above or that fiddle, I just found it while searching for the solution.)

like image 140
Aditya Ponkshe Avatar answered Dec 13 '22 13:12

Aditya Ponkshe