;(function($) {
$.fn.sumtr = function(options) {
var settings = null;
if(typeof options === 'object')
{
settings = options;
}
// extend user settings with default settings
settings = $.extend({}, $.fn.sumtr.defaultSettings, settings || {});
this.each(function() {
var s = []; // we hold the results here
var table = $(this);
var bodyRows = $(this).find(settings.bodyRows);
var summaryRows = $(this).find(settings.summaryRows);
// do nothing if there is nothing to sum
if (bodyRows.length == 0) return;
bodyRows.each(function(index) {
var col = 0;
$(this).children("td").each(function() {
if ($(this).is(settings.sumCells)){
if (s.length < col + 1) s[col] = 0;
var val = settings.readValue($(this));
s[col] = s[col] + val;
} else {
s[col] = "noCount"; // a flag which tells us we're not counting that column
}
var colspan = (parseInt($(this).attr('colspan'))) || 1;
col = col + colspan;
});
});
summaryRows.each(function(index) {
var col = 0;
$(this).children("td").each(function() {
if (s[col] != "noCount"){
$(this).html(settings.formatValue(s[col]));
settings.onSum($(this), s[col]);
}
var colspan = (parseInt($(this).attr('colspan'))) || 1;
col = col + colspan;
});
});
settings.onComplete(table);
});
};
$.fn.sumtr.defaultSettings = {
readValue : function(e) { var r = parseFloat(e.html()); return !isNaN(r) ? r : 0; },
formatValue : function(val) { return val; },
onComplete : function(e) { },
onSum : function(e,sum) { e.data('sumtr', sum); },
sumCells : '.sum',
bodyRows : 'tbody tr',
summaryRows : 'tr.summary',
};
// a related helper
$.fn.sumtrRatio =...
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.