I just installed jQuery Tablesorter plugin and successfully integrated. but raised an issue in my code, ie my table having time values, I want to collect the time values after filtering and calculate its total.
attaching screen shot..
I want to show the total time in below the table but how can I collect the table values?
I just tried the below code..
$('select').on('change', function() {
var colCount = 0;
$('#mytable tbody tr td:nth-child(4)').each(function () {
if ($(this).attr('td')) {
colCount += +1;
} else {
colCount++;
}
});
alert(colCount);
});
To make this work, you'll need a slightly modified version of the duration parser from this answer. Set the parser for that column by adding a "sorter-times"
class name to the header cell.
Then you'll need to include a custom widget to do the calculations (demo):
$(function () {
// change maxDigits to 4, if values go > 999
// or to 5 for values > 9999, etc.
var maxDigits = 3;
// https://stackoverflow.com/a/27023733/145346
$.tablesorter.addParser({
id: "times",
is: function (s) {
return false;
},
format: function (s) {
// prefix contains leading zeros that are tacked
var prefix = new Array(maxDigits + 1).join('0'),
// split time into blocks
blocks = s.split(/\s*:\s*/),
len = blocks.length,
result = [];
// add values in reverse, so if there is only one block
// (e.g. "10"), then it would be the time in seconds
while (len) {
result.push((prefix + (blocks[--len] || 0)).slice(-maxDigits));
}
// reverse the results and join them
return result.length ? result.reverse().join('') : s;
},
type: "text",
parsed: true
});
$.tablesorter.addWidget({
id: 'calcTime',
options: {
calcTime_columns: []
},
format: function (table, c, wo) {
var array, column, time, index, start, end, str,
multiplier = [1, 60, 3600]; // s, m, h
for (column = 0; column < c.columns; column++) {
if ($.inArray(column, wo.calcTime_columns) >= 0) {
array = $.tablesorter.filter.getOptions(table, column, true);
time = 0;
$.each(array, function (i, t) {
console.log(t);
end = t.length;
index = 0;
start = end - maxDigits;
while (start >= 0 && index < maxDigits) {
str = t.substring(start, end);
time += parseInt(str, 10) * multiplier[index];
index++;
start -= maxDigits;
end -= maxDigits;
}
});
}
}
// with more than one column, you'll need to target tfoot
// columns separately
$('tfoot span').html(time + ' seconds');
}
});
$('table').tablesorter({
theme: 'blue',
widgets: ['zebra', 'filter', 'calcTime'],
widgetOptions: {
// target column with a zero-based index
calcTime_columns: [3]
}
});
});
tfoot
, I didn't include any extra coding. If you need it, then I can modify the widget.