Using JavaScript, jQuery, XML, and XSL to bind a grid and automatically calculate column/row totals
This example uses JavaScript and a simple XSL transformation to bind XML data to a grid. The XSL transformation does the initial calculations for the rows and columns. There is also jQuery code to handle the blur() event on the textboxes to update the totals automatically.
// format
String.prototype.format = function () {
var args = arguments;
return this.replace(/{(\d+)}/g, function (match, number) {
return typeof args[number] != 'undefined'
? args[number]
: match
;
});
};
// format number with commas and decimal
Number.prototype.numberFormat = function (decimals, dec_point, thousands_sep) {
dec_point = typeof dec_point !== 'undefined' ? dec_point : '.';
thousands_sep = typeof thousands_sep !== 'undefined' ? thousands_sep : '';
var parts = this.toFixed(decimals).split('.');
parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, thousands_sep);
return parts.join(dec_point);
};
// initialize
$(function () {
// bind data
BindData();
// events
$(".amount").blur(function () {
// variables
var row = $(this).attr("data-row");
var column = $(this).attr("data-column");
var selectorRow = ".total{0}".format(row);
var selectorColumn = ".{0}".format(column);
var selectorAll = ".amount";
var lblTotalRow = $("#lbl-total-{0}".format(row));
var lblTotalColumn = $("#lbl-total-{0}".format(column));
var lblTotalAll = $("#lbl-total-sum");
var totalRow = 0;
var totalColumn = 0;
var totalAll = 0;
// format number
$(this).val(parseFloat($(this).val().replace(/[^0-9$.,]/g, '').replace(/,/g, '').replace(/\$/g, '')).numberFormat(2));
// get value
var amount = $(this).val();
// make sure we still have a valid number
if (amount == 'NaN' || amount == NaN) {
$(this).val('0.00');
}
// calculate total for this row
$(selectorRow).each(function () {
totalRow += Number($(this).val());
});
// calculate total for this column
$(selectorColumn).each(function () {
totalColumn += Number($(this).val());
});
// calculate total for all...
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.
Fiddle Pages
Your fiddles accessible under a custom domain and a vanity path - the simplest hosting for your personal project.
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!
Get Fiddle Pages with PRO
Your fiddles accessible under a custom domain and a vanity path - the simplest hosting for your personal project.