I have a form that is made up of a number of input boxes with class ‘assets’, and an input box at the end with an id of total_assets. I would like the total_assets input box to display the running total as I enter the amounts in the other input boxes.
This is what I have, which is giving me nothing so far. What did I do wrong here?
Well I added that because when I first go to the page with the form and haven’t entered anything yet, the total input box contains a NaN, but I want it to stay blank until I start filling in the form. I tried it with 0 instead, and am getting nothing in the total assets input box.
As I enter amounts in the assets input boxes, the running total should be displaying dynamically in the total assets box.
AFAIK, jQuery.each.on is not a function. I think you want this:
var $assets = $(".budget .assets"),
$totalAssets = $('#total_assets');
$assets.on('blur', function() {
var sum = 0;
assets.each(function() {
var value = parseFloat($(this).val());
if (!isNaN(value)) sum += value;
});
$totalAssets.text(sum);
});
@timseverien - you had > $totalAssets.text(sum); to display the value in the #totalAssets form input box. Should that be $totalAssets.value = sum; because it is an input box? or does it make a difference? (You can tell I am really rusty with jQuery and JavaScript.)
Another question: if I want a running total that will change as each amount is entered, should I not move the $totalAssets.text(sum); up into the $assets.each(function() so that it reads like this?
var $assets = $(".budget .assets"), $totalAssets = $("#total_assets");
$assets.on('blur', function() {
var assetsSum = 0;
$assets.each(function(){
var assetsValue = parseFloat($(this).val());
if (!isNaN(incomeValue)) {
assetsSum += assetsValue;
}
//$totalAssets.value = assetsSum;
$totalAssets.text(assetsSum);
});
});