-
Notifications
You must be signed in to change notification settings - Fork 751
Description
I don't know if you plan to add this, but I couldn't find a good example out there. So I wrote my own custom widget to do this. I will include it here for anyone to use/enhance, etc. Maybe it can become part of a future release? So consider this an enhancement request. I do not consider myself a javascript guru, but have the basics all down. and I am using this in one of my pages.
Setup:
Create a tfoot section to your table with the same columns as your header. Add a class with the name of sum for summing up the contents of the column. I expect I will add more in the future, such as count to count the number of rows, avg to calculate the average, etc. Not sure what else. tfoot example:
<tfoot> <tr> <td>Project Id</td> <td>Customer Name</td> <td class="sum">Total Hours</td> <td class="sum">Budget Hours</td> <td>Project Status</td> </tr> </tfoot>
This is a 5 column table with totals in two of the columns. The code will replace all values with an empty string or the calculated total.
Here is the widget add on code:
// addWidget tmTotals
// ******************* Written by Tim Miller
$.tablesorter.addWidget({
id: 'tmTotals',
// The init function (added in v2.0.28) is called only after tablesorter has
// initialized, but before initial sort & before any of the widgets are applied.
init: function(table, allWidgets, thisWidget){
// widget initialization code - this is only *RUN ONCE*
// but in this example, only the format function is called to from here
// to keep the widget backwards compatible with the original tablesorter
thisWidget.format(table, true);
},
format: function(table, initFlag) {
// widget code to apply to the table *AFTER EACH SORT*
// the initFlag is true when this format is called from the init
// function above otherwise initFlag is undefined
// * see the saveSort widget for a full example *
mytablefoot = table.getElementsByTagName("tfoot")[0];
for(var i = 0; i < mytablefoot.rows[0].cells.length; i++)
{
if (mytablefoot.rows[0].cells[i].className == "sum") {
var subTotal = 0;
mytablebody = table.getElementsByTagName("tbody")[0];
for(var j = 0; j < mytablebody.rows.length; j++)
{
if (mytablebody.rows[j].style.display != "none") {
subTotal = parseFloat(subTotal) + parseFloat(mytablebody.rows[j].cells[i].innerHTML);
}
}
mytablefoot.rows[0].cells[i].innerHTML = subTotal;
} else {
mytablefoot.rows[0].cells[i].innerHTML = "";
}
}
}
});
I only have the sum function in there now as that is all I currently need. I can see a need for specifying the formatting of the total, too. And making sure it handles all number types.
I am open to improvements on this and would love to see this in the baseline some day, some kind of functionality like this at least.