Alexander Ruben
Alexander Ruben

Reputation: 45

Sorting HTML table with empty cells placed at the bottom

I'm using this answer here - sort html table with jquery to properly sort my HTML table. However, I would like to simply sort the table with all of the empty TD cells at the bottom. Does anyone have a simple tweak to do this? Here's my exact code -

   $('#sortAnniv').click(function() {
    var table = $('#myTable')
    var rows = table.find('tr:gt(0)').toArray().sort(comparer($(this).index()))
    this.asc = !this.asc
    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() }

Upvotes: 0

Views: 284

Answers (1)

ControlAltDel
ControlAltDel

Reputation: 35051

just add a case for it

function comparer(index) {
    return function(a, b) {
        var valA = getCellValue(a, index), valB = getCellValue(b, index)
        // Add this line
        if (valA.length === 0) return 1; if (valB.length === 0) return -1;
        return $.isNumeric(valA) && $.isNumeric(valB) ? valA - valB : valA.toString().localeCompare(valB)
    }
}

Upvotes: 1

Related Questions