jQuery table sort

tony noriega picture tony noriega · Jul 1, 2010 · Viewed 259.1k times · Source

I have a very simple HTML table with 4 columns:

Facility Name, Phone #, City, Specialty

I want the user to be able to sort by Facility Name and City only.

How can I code this using jQuery?

Answer

Nick Grealy picture Nick Grealy · Nov 13, 2013

I came across this, and thought I'd throw in my 2 cents. Click on the column headers to sort ascending, and again to sort descending.

  • Works in Chrome, Firefox, Opera AND IE(8)
  • Only uses JQuery
  • Does alpha and numeric sorting - ascending and descending

$('th').click(function(){
    var table = $(this).parents('table').eq(0)
    var rows = table.find('tr:gt(0)').toArray().sort(comparer($(this).index()))
    this.asc = !this.asc
    if (!this.asc){rows = rows.reverse()}
    for (var i = 0; i < rows.length; i++){table.append(rows[i])}
})
function comparer(index) {
    return function(a, b) {
        var valA = getCellValue(a, index), valB = getCellValue(b, index)
        return $.isNumeric(valA) && $.isNumeric(valB) ? valA - valB : valA.toString().localeCompare(valB)
    }
}
function getCellValue(row, index){ return $(row).children('td').eq(index).text() }
table, th, td {
    border: 1px solid black;
}
th {
    cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
    <tr><th>Country</th><th>Date</th><th>Size</th></tr>
    <tr><td>France</td><td>2001-01-01</td><td>25</td></tr>
    <tr><td><a href=#>spain</a></td><td>2005-05-05</td><td></td></tr>
    <tr><td>Lebanon</td><td>2002-02-02</td><td>-17</td></tr>
    <tr><td>Argentina</td><td>2005-04-04</td><td>100</td></tr>
    <tr><td>USA</td><td></td><td>-6</td></tr>
</table>

** Update: 2018