Chad Chad - 4 months ago 17
jQuery Question

jQuery table sort code only working in Mozilla Firefox

I used charlietfl's answer to this question in StackOverflow to sort the months column in my HTML table from January to December. I just modified a few things so I could use it on my Website. I am also using tablesorter so I could sort the other table columns alphabetically. The problem is that it only works on Mozilla Firefox. Other browsers won't sort the months column. Sometimes
the tr that wraps the table headers jump out of the thead tag and goes inside the tbody tag. Here's my table: http://makzel.com/problems/

What could be causing this?

Here's my full jquery code:

(function($) {

'use strict';

var $window = $(window);

$window.ready(function(){

// Enable sorting for tables
$(".tablesort").tablesorter({
headers: {
0: {
sorter: false
}
}
});

// Sort by month
$('.tablesort th').click(function(){
var sorters =['January','February','March','April','May','June','July','August','September','October','November','December']

var $rows = $('tr:gt(0)').sort(function(a, b){
var aSrcIdx =sorters.indexOf( $(a).find('td:first').text() );
var bSrcIdx = sorters.indexOf( $(b).find('td:first').text());

return aSrcIdx > bSrcIdx;
});

$(this).closest('.tablesort').append($rows);
});

// Tablesort header background change on click
$(".tablesort th").click(function(){
$('.tablesort th').not(this).removeClass('sorted');
$(this).toggleClass('sorted');
});

function postOverflow() {
if ($window.width() < 768) {
$('.tablesort').closest('.post').css("overflow","scroll");

} else{
$('.tablesort').closest('.post').css("overflow","none");
}
}
postOverflow();
$window.resize(postOverflow);

}); // Ready

})(jQuery);


Here's the link of it showing the tr tag jumping out of the thead tag: http://cms5.revize.com/revize/haddonfield/departments/table_sort_test/index.php

Answer

According to the documentation of array.sort, try returning -1 to put a below b, 0 to leave them unchanged, or 1 to put b below a. Try replacing:

return aSrcIdx > bSrcIdx;    

with

return aSrcIdx < bSrcIdx ? -1 : bSrcIdx < aSrcIdx ? 1 : 0;    
Comments