Following this post jQuery table sort (github link: https://github.com/padolsey/jQuery-Plugins/blob/master/sortElements/jquery.sortElements.js), I am successfully sort columns,
Conditions for the code to work:
tds with rowspan must all be on the left of the tabletds in these columns must have a rowspan, even if it's 1jsFiddle: http://jsfiddle.net/5GrAC/77/
var inverse = false;
function sortColumn(index) {
var trs = $('#resultsTable > tbody > tr'),
nbRowspans = trs.first().children('[rowspan]').length,
offset = trs.first().children('[rowspan]').last().offset().left;
var tds = trs.children('[rowspan]').each(function() {
$(this).data('row', $(this).parent().index());
$(this).data('column', $(this).index());
$(this).data('offset', $(this).offset().left)
}).each(function() {
if($(this).data('offset') != offset)
return;
var rowMin = $(this).data('row'),
rowMax = rowMin + parseInt($(this).attr('rowspan'));
trs.slice(rowMin, rowMax).children().filter(function() {
return $(this).index() == index + $(this).parent().children('[rowspan]').length - nbRowspans;
}).sortElements(function(a, b) {
a = convertToNum($(a).text());
b = convertToNum($(b).text());
return (
isNaN(a) || isNaN(b) ?
a > b : +a > +b
) ?
inverse ? -1 : 1 :
inverse ? 1 : -1;
}, function() {
return this.parentNode;
});
});
var trs = $('#resultsTable > tbody > tr');
tds.each(function() {
if($(this).parent().index() != $(this).data('row'))
$(this).insertBefore(trs.eq($(this).data('row')).children().eq($(this).data('column')));
});
inverse = !inverse;
}
Quick explanations:
tds with rowspantds are saved, including left offsettds are filtered by their original offset to work only with the rightmost onestrs related to each kept td are sorted using the wanted columntds with rowspan are finally moved back to their original position if necessaryAbout question 2, I will only complete bartlaarhoven's answer by saying, the code can also be written like the following:
return (
(isNaN(a) || isNaN(b) ? a > b : +a > +b) ? 1 : -1
) * (inverse ? -1 : 1);
You can easily read that inverse is used to inverse the result.