Click here to Skip to main content
11,503,113 members (74,951 online)
Click here to Skip to main content

Sort Every HTML Table in Few Lines of JavaScript Code

, 24 Mar 2015 CPOL 4.8K 16
Rate this:
Please Sign up or sign in to vote.
The most lightweight and easy function to sort a table

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

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Member 11000643
Engineer
United Kingdom United Kingdom
No Biography provided

Comments and Discussions

 
-- There are no messages in this forum --
| Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.150520.1 | Last Updated 24 Mar 2015
Article Copyright 2015 by Member 11000643
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid