Reputation: 219
Ive worked for a few days on this one. I have a script that is dynamically creating rows in a table. The final output looks like this:
<table id="event-list">
<tr id="event0" value="04/04/2000">
<td>My Third Event</td>
<td>Apr 4</td>
<td>Omaha, NE</td>
<td></td>
</tr>
<tr id="event4" value="04/24/2000">
<td>USA Triathlon National Championships Collegiate Club</td>
<td>Apr 24</td><td>Clemson, SC</td>
<td></td>
</tr>
<tr id="event2" value="07/17/2000">
<td>My Second Event</td><td>Jul 17</td>
<td>Omaha, NE</td>
<td></td>
</tr>
<tr id="event3" value="08/17/2000">
<td>My Second Event</td>
<td>Aug 17</td>
<td>Ames, IA</td>
<td></td>
</tr>
<tr id="event1" value="10/26/2000">
<td>ZTA 5K For Breast Cancer Awareness</td>
<td>Oct 26</td>
<td>Omaha, NE</td>
<td></td>
</tr>
</table>
Im using the below script to sort each row by date:
$('#event-list tr').sort(function(a,b) {
return new Date($(a).attr('value')) < new Date($(b).attr('value'));
}).each(function(){
$('#event-list').prepend(this);
});
It works fine in Chrome and Firefox, but in IE - the list is just reversing in the opposite order.
Any thoughts on a reason or work around? Thanks in advance.
Upvotes: 1
Views: 820
Reputation: 28870
Your sort function is incorrect. A sort function can't just return a boolean telling whether one element is greater than the other. It has to handle all three cases: less than, greater than, and equal.
It's easy to change your sort function to accomplish this. Instead of comparing the two values with the <
operator, simply subtract them:
return new Date($(a).attr('value')) - new Date($(b).attr('value'));
If that gives you the opposite order from what you want, reverse it:
return new Date($(b).attr('value')) - new Date($(a).attr('value'));
Upvotes: 3