Reputation: 572
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.
Upvotes: 1
Views: 777
Reputation: 1072
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 y-x or x-y.
http://jsbin.com/nalomuje/23/edit
Upvotes: 2