HTML | Make HTML table sortable on column click

|
| By Webner

When we need to sort an HTML table on click of any of its column headers then we can use sortable.js:

Download library file sorttable.js.
Add this js file to the current page.
Add sortable class to the table for which sorting is required.

If you have many tables on the current page and you want every table to be sortable then add this function to any of your js file included in the page and call this function onload of the page:

function makeAllSortable() {
    parent = document.body;
    var t = parent.getElementsByTagName('table'),
    i = t.length;
    while (--i >= 0) {
    if (t[i].id.length != 0) {
    $j('#' + t[i].id).addClass("sortable");
    sorttable.makeSortable(document.getElementById(t[i].id));
    } else
    {
    t[i].id = "table" + i;
    $j('#table' + i).addClass("sortable");
    sorttable.makeSortable(document.getElementById('table' + i));
    }
  }
}

Leave a Reply

Your email address will not be published. Required fields are marked *