简体   繁体   中英

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() }

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)
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM