简体   繁体   中英

Ignoring empty cells while sorting table rows using jQuery

I am trying to sort the table rows without any plugin. Unfortunately I don't have an option to use a plugin. Well here's what I have tried till now:

var info = $('#project_table tr.punch_list_summary');
    //For Closed Date
    $(document).on('click', '#descending_closed_date', function(e) {
        e.preventDefault();
        var sortDir = -1;
        info.sort(function(a, b) {
            if ($(a).attr('data-closeddate') === 'null') {
                if ($(b).attr('data-closeddate') === 'null') {
                    return false;
                }
                return true;
            }
            a = new Date($(a).attr('data-closeddate'));
            b = new Date($(b).attr('data-closeddate'));
            return (a - b) * sortDir;
        });
        $('#project_table').html(info);
        sortDir = 1;
    });

    $(document).on('click', '#ascending_closed_date', function(e) {
        e.preventDefault();
        var sortDir = 1;
        info.sort(function(a, b) {
            if ($(a).attr('data-closeddate') === 'null') {
                if ($(b).attr('data-closeddate') === 'null') {
                    return false;
                }
                return true;
            }
            a = new Date($(a).attr('data-closeddate'));
            b = new Date($(b).attr('data-closeddate'));
            return (a - b) * sortDir;
        });
        $('#project_table').html(info);
        sortDir = -1;
    });

});

As you can see I am using data-attribute to sort the rows. The Closed Date column can be empty or can have a date. The issue is it just sorts random rows, moreover, I am trying to bring all empty rows at the bottom and the rows with Closed Date at the top. What I might be doing wrong?

Here's the working jsbin for those who want to see what I have done till now. I would really appreciate any help.

UPDATE

Here's an updated jsbin . I can sort by closed date now but it still doesn't force the rows with empty closed dates to bottom.

If descending and the data is "null", make the data as 1 Jan 1900 (so it will be at the bottom) If ascending and the data is "null", make the data as 1 Jan 9999 (so it will be at the bottom)

Then do a normal comparison yx or xy.

http://jsbin.com/nalomuje/23/edit

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