Sort Every HTML Table in Few Lines of JavaScript Code - CodeProject

:

Introduction

I got the code from the internet. My contribution was make the algorithm 'universally' applicable using callbacks.

Background

You need to have a basic knowledge of JavaScript.

Using the Code

For a live example, go here.

This is the function:

M22.TableSort.sort = function (e, getValue) {
    try {

        debugger;

        var cellIndex = e.currentTarget.cellIndex;
        var th = $(e.currentTarget);
        var tbody = th.closest('table')[0].tBodies[0];
        
        var className = (th.hasClass('sortAZ')) ? 'sortZA' : 'sortAZ';
        
        th.closest('tr').find('th.sortAZ, th.sortZA')
            .removeClass('sortAZ')
            .removeClass('sortZA')
            .addClass('sortNO');
            
        th.removeClass('sortNO');    
        th.addClass(className);
        
        var direction = (className == 'sortAZ') ? 1 : -1;
        
        var rows = tbody.getElementsByTagName("tr"); 
        rows = Array.prototype.slice.call(rows,0);         
        
        rows.sort(function (rowA, rowB) {
            var valueA = getValue(rowA, cellIndex);
            var valueB = getValue(rowB, cellIndex);
            
            return (valueA <= valueB) ? -direction : direction;
        });

        for (x in rows) { tbody.appendChild(rows[x]) };
    
    }
    catch (jse) {
        if (console) if (console.error) console.error(jse)
    }
}

and this is the most representative example on how to use the function. It is based on the column 'Category' which has a custom sorting criteria.

MeTita.TableSort.thCategory_click = function (e) {
    try {

        // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
        //  This function is the 'responsibility' of the developer. The developer knows: 
        //   1) how to get the cell value;
        //   2) which is the sort criteria.
        function getValue(tr, cellIndex) {

            var category = $(tr.children[cellIndex]).text();

            // this is an ordered list to set a custom priority! 
            // Rows will be sorted following this order.
            var categories = ['Standard', 'Economy', 'Deluxe', 'Suite'];

            return categories.indexOf(category);
        }
        // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

        // getCellValue 'knows' how to sort rows
        M22.TableSort.sort(e, getValue);

    }
    catch (jse) {
        alert(jse.message);
    }
}

and this is the code that attaches the function to the column click handler.

MeTita.TableSort.document_ready = function (divContainer) {
    try {
        var tblRooms = $("#tblRooms", divContainer);

        $('tr th.room_category', tblRooms)
            .click(MeTita.TableSort.thCategory_click);
    }
    catch (jse) {
        alert(jse.message);
    }
}

Points of Interest

Sorting a table is a task that involves three main steps:

  1. Defining a sorting criteria: alphabetical; numeric; custom 
  2. Get the value to sort from the content of the table cell
  3. Sorting 

Step 3 is a classic exercise for beginners! Here, the sorting is obtained with a technique that is a little bit more advanced:

rows.sort(function (rowA, rowB) {
    var valueA = getValue(rowA, cellIndex);
    var valueB = getValue(rowB, cellIndex);

    return (valueA <= valueB) ? -direction : direction;
});

The calback function 'getValue(row, cellIndex)' solves the problems that are in points 1 and 2.

What does this mean?

Point 1 and point 2 (potentially) can change for every HTML table, and only the developer knows how to cope with this problem, so the function 'M22.TableSort.sort'  'asks the developer' how to do!

The developer writes the body of getValue as in 'MeTita.TableSort.thCategory_click'. This function has the responsibility to find the value used for sort (not necessarily the displayed value).

var category = $(tr.children[cellIndex]).text();

and assign to it a 'sortable' value.

// this is an ordered list to set a custom priority!
// Rows will be sorted following this order.
var categories = ['Standard', 'Economy', 'Deluxe', 'Suite'];

return categories.indexOf(category);

History

  • First release but is stable enough