Dean.DePue Dean.DePue - 1 month ago 17
jQuery Question

Sorting a Table with jQuery

I have found and followed an example on here for sorting a table but it does not work. Here is my code:

function comparer(index) {
return function (a, b) {
var valA = getCellValue(a, index), valB = getCellValue(b, index);
return $.isNumeric(valA) && $.isNumeric(valB) ? valA - valB : valA.localeCompare(valB);
}
}

function getCellValue(row, index) {
return $(row).children('td').eq(index).html();
}

function sortTable(header) {
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 createTableHeader(table, headers, alignment) {
if (headers.length > 0) {
var thead = document.createElement('thead');
table.appendChild(thead);
var tr = document.createElement('tr');
for (var i = 0; i <= headers.length - 1; i++) {
var th = document.createElement('th');
var text = document.createTextNode(headers[i]);
th.appendChild(text);
th.style.textAlign = alignment;
th.setAttribute('onclick', sortTable)
tr.appendChild(th);
}
thead.appendChild(tr);
}
}


Nothing happens at all, and yet, when I look at the details I can see the function attached to the TH element. ANy ideas?

Does the fact that I am creating this table on the fly with data received from an AJAX call have anything to do with the problem?

Answer

Here is what I did to make it work:

 function createTableHeader(table, headers, alignment) {
if (headers.length > 0) {
    var thead = document.createElement('thead');
    table.appendChild(thead);
    var tr = document.createElement('tr');
    for (var i = 0; i <= headers.length - 1; i++) {
        var th = document.createElement('th');
        var text = document.createTextNode(headers[i]);
        th.appendChild(text);
        th.style.textAlign = alignment;
        th.style.cursor = 'pointer';
        th.setAttribute('title', "Sort by " + headers[i]);
        th.onclick = function () {
            var rows = $(table).find('tbody').find('tr').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]);
            }
        }
        tr.appendChild(th);
    }
    thead.appendChild(tr);
}
}
Comments