Sort HTML Table using JQuery


To sort a table we can use JQuery sort.
This can be implement after the UI is completely loaded. So, we don’t need to do anything on server side.

Sample table format
<table class=”data-table”>
<thead>
<tr>
                <th>col 1</th>
                <th>col 2</th>
</tr>
</thead>
<tbody>
<tr>
                <td>val 1</td>
                <td>asdf</td>
</tr>
<tr>
                <td>val 2</td>
                <td>asdf</td>
</tr>
.. Any number of rows….
</ tbody >
<table>

Source
$('.data-table').SortTable();

$.fn.SortTable = function () {
        var tableHandler = $(this);
        var rows = tableHandler.find("tbody tr").get();
        rows.sort(function (a, b) {
            var aValue = $(a).children("td").eq(0).text().toUpperCase();
            var bValue = $(b).children("td").eq(0).text().toUpperCase();
            if (aValue < bValue) {
                return -1;
            }
            if (aValue > bValue) {
                return 1;
            }
            return 0;
        });
        $.each(rows, function (index, row) {
            tableHandler.children("tbody").append(row);
        });

};

Comments