Yesterday I got great help resolving a $NaN issue so hoping I can get another answer in my code from yesterday, subtotal is adding the totals at the end of each line now and showing a value so that is good, however anytime I enter an amount sold and then go and change that value it adds again, so if I set quantity to 2 and its $50 per, the total for the line item is $100 and the subtotal reflects, but if I change the quantity to 1 the line item becomes $50 correctly, but the subtotal re-adds and becomes $150, I’m not savvy enough with JS to see what I’m doing wrong…
$(document).ready(function() {
var subtotal = 0;
var stantot = 0;
var showtot = 0;
$("input").keyup(function() {
for (var i = 0; i <= 30; i++) {
var unitp = parseFloat($("#unitp" + i).val()) || 0;
var casep = parseFloat($("#casep" + i).val()) || 0;
var units = parseFloat($("#units" + i).val()) || 0;
var cases = parseFloat($("#cases" + i).val()) || 0;
var st_disc = parseFloat($("#st_disc").val()) || 0;
var sh_disc = parseFloat($("#sh_disc").val()) || 0;
var unitr = (unitp * units);
var caser = (casep * cases);
var result = (unitr + caser);
var st_disc_fix = (st_disc / 100);
var sh_disc_fix = (sh_disc / 100);
var st_disc_solo = (st_disc_fix * result);
var sh_disc_solo = (sh_disc_fix * result);
var disc_total = (st_disc_fix + sh_disc_fix);
var disc_whole = (disc_total * result);
var disc = (result - disc_whole);
var st_disc_tot = (result - disc_whole);
var sh_disc_tot = (result - disc_whole);
$("#line" + i).val(result.toFixed(2));
$("#disc" + i).val(disc.toFixed(2));
subtotal += parseFloat((unitp * units) + (casep * cases));
stantot += parseFloat(st_disc_tot);
showtot += parseFloat(sh_disc_tot);
}
$("#totretail").val(subtotal.toFixed(2));
$("#standiscount").val(stantot.toFixed(2));
$("#showdiscount").val(showtot.toFixed(2));
var totship = ($("#totship").val() * 1);
var tottax = ($("#tottax").val() * 1);
var finaltotal = (subtotal + stantot + showtot + totship + tottax);
$("#total").val(finaltotal.toFixed(2));
});
});
Move
var subtotal = 0;inside theinputlistener, so your subtotal is recalculated each time:..
otherwise total will keep growing, the reason
stantotandshowtotare working is because they are set from a var with=not+=.I moved the other vars in there also, just because it’s better.