Reputation: 1442
I have some sales data which is loaded into a ul by ajax with an id of ajaxInner. Unfortunately these li's are not appended in time order. How do I create a JavaScript function to sort these li's into time order by the time in the transactTime span. I would like this as a function I can call after each new li is appended so it takes account of all the li's in the list and reorders them accordingly by the time.
<ul id="ajaxInner">
<li><span class="transactTime">10:13 - </span><span class="transactAmount">£444</span><br><img src="images/orangeMarker.png" class="mapMarker"><span class="transactCity">Stoke-on-trent (Stoke-On-Trent, United Kingdom)</span></li>
<li><span class="transactTime">10:08 - </span><span class="transactAmount">£56</span><br><img src="images/orangeMarker.png" class="mapMarker"><span class="transactCity">Belper (Derbyshire, United Kingdom)</span></li>
<li><span class="transactTime">10:15 - </span><span class="transactAmount">£39</span><br><img src="images/orangeMarker.png" class="mapMarker"><span class="transactCity">Stoke-on-trent (Stoke-On-Trent, United Kingdom)</span></li>
<li><span class="transactTime">10:14 - </span><span class="transactAmount">£459</span><br><img src="images/orangeMarker.png" class="mapMarker"><span class="transactCity">Belper (Derbyshire, United Kingdom)</span></li>
<li><span class="transactTime">10:16 - </span><span class="transactAmount">£1057</span><br><img src="images/orangeMarker.png" class="mapMarker"><span class="transactCity">Scarborough (North Yorkshire, United Kingdom)</span></li>
<li><span class="transactTime">10:11 - </span><span class="transactAmount">£107</span><br><img src="images/orangeMarker.png" class="mapMarker"><span class="transactCity">Scarborough (North Yorkshire, United Kingdom)</span></li>
</ul>
Code I've tried so far:
//sort the li's into time order
function sortList() {
var ul = $('#ajaxInner');
var li = ul.children("li");
li.detach().sort();
ul.append(li);
}
However this doesn't always sort by time order and you get some odd results with times at the top which shouldn't be.
Upvotes: 1
Views: 308
Reputation: 58442
try this:
function sortList() {
var ul = $('#ajaxInner');
var li = ul.children("li");
li.detach().sort(function(a, b) {
var date1 = new Date (new Date().toDateString() + ' ' + $(a).children('span.transactTime').text().substr(0,5))
var date2 = new Date (new Date().toDateString() + ' ' + $(b).children('span.transactTime').text().substr(0,5))
var result = (date1 < date2) ? -1 : (date1 > date2) ? 1 : 0
return result;
});
ul.append(li);
}
Upvotes: 2