简体   繁体   中英

How to sort a table column by clicking on the header in Jquery?

I want to sort a table column strings values by clicking on table header. here I did alphabets sorting. please change this code to String column sorting.

enter code here
  var  sortOrder = -1;
    $(".sort").click(function () {
        sortOrder *= -1;
     sortTable($(this));
     });


  function sortTable(element) {
    var tbody = element.parent();
    var colIndex = element.index() -1;
    tbody.find('tr').sort(function (a, b)
    {
        $('td', a).eq(colIndex).text() === "" ? $('td', a).eq(colIndex).text("0") :   $('td', a).eq(colIndex).text();
        if (sortOrder === 1)
        {
            return parseInt($('td', a).eq(colIndex).text(), 10) - parseInt($('td', b).eq(colIndex).text(), 10);
        }
        else
        {
            return parseInt($('td', b).eq(colIndex).text(), 10) - parseInt($('td', a).eq(colIndex).text(), 10);
        }

    }).appendTo(tbody);
    tbody.find('tr').each(function () {
        $(this).removeClass();
        zebra = zebra === 'odd' ? 'even' : 'odd';
        $(this).addClass(zebra);
        $(this).find("td").eq(colIndex).text() === 0 ? $(this).find("td").eq(colIndex).text(""):$(this).find("td").eq(colIndex).text(); 
    });
}

use the jquery datatable js there you will get sorting option as default and also you can use more options called filter,pagination,etc... reference

$(document).ready(function(){
    $('#myTable').DataTable();
});

这是一个用于对表格进行排序的 jQuery 插件: http : //tablesorter.com/

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