> How could this be modified to allow summing multiple sets of textboxes
> (using each set using a different class name) into multiple total
> textboxes (again using different class names)? Can this somehow be
> converted to a function, or can the selectors be dynamically modified
> some way?
This is untested, but something like this should do it:
(function($){
$.fn.total = $.extend(function(selector) {
var total = 0, initialText, totalBox = $(selector);
this.each(function() {
var additional =
total += $.fn.total.orZero(parseInt(this.value));
$(this).focus(function() {
initialText = $.fn.total.orZero(this.value);
}).blur(function() {
if (this.value != initialText) {
total = $.fn.total.orZero(parseInt(totalBox.html
()));
total -= initialText;
total += $.fn.total.orZero(parseInt(this.value));
totalBox.html(total);
}
});
});
totalBox.html(total);
return this;
}, {orZero: function(value) {return isNaN(value) ? 0 : value;}});
})(jQuery);
You would use it like this:
$(document).ready(function() {
$("input").total("#grand-total");
});
or
$(document).ready(function() {
$(".additem").total(".totalitem");
});
or
$(document).ready(function() {
for (var i = 1; i < 5; i++) {
$(".row" + i).total("#row" + i + "-total");
}
for (var i = 1; i < 4; i++) {
$(".column" + i).total("#column" + i + "-total");
}
});
This does check for non-numerics, which the original didn't (the orZero
() function.) Otherwise, it's closely modeled on the code you
supplied.
No comments:
Post a Comment