John Stab John Stab - 4 months ago 11
Javascript Question

JS table sort by checkbox

I have a table with multiple data types on columns (date, string, int and checkbox). I want to sort it by the checked property of the checkbox.

I have done most of the function but I am stuck in getting the checkbox value from the

td
.

$tbody.find('tr').sort(function (a, b) {
var tda = checkboxSort ? $(a).find('td:eq(' + columnNumber + ')').find('checkbox').val() : $(a).find('td:eq(' + columnNumber + ')').text().toLowerCase();
var tdb = checkboxSort ? $(b).find('td:eq(' + columnNumber + ')').find('checkbox').val() : $(b).find('td:eq(' + columnNumber + ')').text().toLowerCase();
//...other sortings based on type

if (ascending) {
return tda < tdb ? -1 : tda > tdb ? 1 : 0;
} else {
return tdb < tda ? -1 : tdb > tda ? 1 : 0;
}
}).appendTo($tbody);


Here "checkboxSort ? $(a).find('td:eq(' + columnNumber + ')').find('checkbox').val()" i cant manage to sort it out.

Can someone help me?
Thanks!

Answer

I hope it will works, I am not sure about it. because I have not tested from my side as you have mentioned other variables also. Still I have tried my best

var $tr = $tbody.find('tr');

var sorted_tr= $tr.sort(function (a, b) {
    var tda = checkboxSort ? $(a).find('td:eq(' + columnNumber + ') checkbox').is(':checked') : $(a).find('td:eq(' + columnNumber + ')').text().toLowerCase();
    var tdb = checkboxSort ? $(b).find('td:eq(' + columnNumber + ') checkbox').is(':checked') : $(b).find('td:eq(' + columnNumber + ')').text().toLowerCase();
    //...other sortings based on type

    if (ascending) {
        return tda < tdb ? -1 : tda > tdb ? 1 : 0;
    } else {
        return tdb < tda ? -1 : tdb > tda ? 1 : 0;
    }
});

$tbody.html(sorted_tr);
Comments