Owen Owen - 1 month ago 6
Javascript Question

Sorting a table using jQuery based on date values

I'm having a problem very similar to this question: jQuery table sort

When the Date header is clicked, I want to sort the table rows based on the dates, not based on the text.

I've based my code on this jsFiddle http://jsfiddle.net/gFzCk/ which was one of the answers to the above question, and it does sort, but it treats the date as normal text, not as a date.

Normally I'd be able modify the original code to suit my needs, but this code is just a little beyond me.

Here's my jsFiddle http://jsfiddle.net/S6dM6/

HTML

<table>
<tr>
<th id="dateHeader">Date</th>
<th>Phone #</th>
<th id="city_header">City</th>
<th>Speciality</th>
</tr>
<tr>
<td>01/02/2013</td>
<td>00001111</td>
<td>Amsterdam</td>
<td>GGG</td>
</tr>
<tr>
<td>24/02/2013</td>
<td>55544444</td>
<td>London</td>
<td>MMM</td>
</tr>
<tr>
<td>28/02/2013</td>
<td>33332222</td>
<td>France</td>
<td>RRR</td>
</tr>
<tr>
<td>13/02/2013</td>
<td>88884444</td>
<td>Auckland</td>
<td>AA</td>
</tr>
<tr>
<td>04/02/2013</td>
<td>11115555</td>
<td>New York</td>
<td>BBB</td>
</tr>
</table>


JS

var table = $('table');

$('#dateHeader')
.wrapInner('<span title="sort this column"/>')
.each(function(){

var th = $(this),
thIndex = th.index(),
inverse = false;

th.click(function(){

table.find('td').filter(function(){

return $(this).index() === thIndex;

}).sortElements(function(a, b){

return $.text([a]) > $.text([b]) ?
inverse ? -1 : 1
: inverse ? 1 : -1;

}, function(){

// parentNode is the element we want to move
return this.parentNode;

});

inverse = !inverse;

});

});


And this js file is referenced:
https://raw.github.com/padolsey/jQuery-Plugins/master/sortElements/jquery.sortElements.js

Just in case you're going to suggest some kind of table sorting plugin, note that my end result wont be sorting when the header is clicked, the sort function will be called from various places in my javascript, I'm just using this click example as a simple starting point to get the concept working and as a simple way to put this question.

AC1 AC1
Answer

Modify your sortElements method like this:

        }).sortElements(function(a, b){

            var strDate = $.text ([a]);
            var dateParts = strDate.split("/");
            var date = new Date(dateParts[2], (dateParts[1] - 1), dateParts[0]);
            var a1 = date.getTime ();
            strDate = $.text ([b]);
            dateParts = strDate.split("/");
            date = new Date(dateParts[2], (dateParts[1] - 1), dateParts[0]);
            b1 = date.getTime ();

            return a1 > b1 ?
                inverse ? -1 : 1
                : inverse ? 1 : -1;