简体   繁体   中英

Sort table column by date in ajax

I have a table that's displayed on button click using ajax. Here's a code snippet:

myBtn.on("click", function() {
    displayTable();
});

function displayTable(){
    $.ajax({
        url:'url to a function in controller',
        type: "GET",
        //data: {val : val},
        dataType: 'json',
        success: function(data){  

            // some codes here

            $.each(data.documents, function(key, value){                        
                $("#myTable")
                .append(
                    "<tr class='" + rowClass + "'><td class='text-center'>" +                       
                        value.title +
                    "</td><td class='text-center'>" +               
                        value.time1.replace(/-/g, "/") +
                    "</td><td class='text-center'>" +                  
                        value.time2.replace(/-/g, "/") +
                    "</td></tr>"
                );
            });
        }
    });
}

After this, a table is displayed but it is not sorted by date ( value.time2 ). I tried this but not working:

$("#myTable thead tr").find('th').eq(3).sort(function(a,b){
    return new Date($(a).value.time2) > new Date($(b).value.time2);
});

Do you have any idea how to do this? How do I sort it by date ( value.time2 )?

The best way would be to request the server to sort the values for you. However, if you need to perform this on client side, you can simply sort data.documents before adding it to the page. For example:

        data.documents = data.documents.map(function(item) {
            // Fix display
            item.time1 = item.time1.replace(/-/g, "/");
            item.time2 = item.time2.replace(/-/g, "/");
            return item;
        });
        data.documents.sort(function(a, b) {
            // Custom sorting function
            return new Date(a.time2) > new Date(b.time2);
        });

        $.each(data.documents, function(key, value){                        
            $("#myTable")
            .append(
                "<tr class='" + rowClass + "'><td class='text-center'>" +                       
                    value.title +
                "</td><td class='text-center'>" +               
                    value.time1 +
                "</td><td class='text-center'>" +                  
                    value.time2 +
                "</td></tr>"
            );
        });

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