Problem with running totals in jquery

Posted by rshivers on Stack Overflow See other posts from Stack Overflow or by rshivers
Published on 2010-05-27T15:28:26Z Indexed on 2010/05/27 15:31 UTC
Read the original article Hit count: 159

Filed under:
|

I'm having an issue trying to get an accurate running total for my calculations. When you enter numbers into the input field I get an accurate total for that line item, but the grand total comes out to a higher number. Note that this is a dynamic form and that the id's will change depending on how many form fields I have added to the form. Also, I have it set to make the calculations onKeyUp for each input field instead of a calculate button.

The code that calculates a single item is this:

function calcLineItem(id) {
    var id = $(id).attr("id");
    var Item1 = $("#Item1" + id).val();
    var Item2 = $("#Item2" + id).val();
    var Item3 = $("#Item3" + id).val();

    function calcTotal(Item1, Item2, Item3){
        var total;
        total = Math.round((Item1 * Item2) * Item3);
        return total;
    }

    $("#total" + id).text(calcTotal(Item1, Item2, Item3));

    calcAllFields();
}

This will give me the total of this particular input field. The function at the end, calcAllFields(), is supposed to do the calculations for all items in my form to give me the grand total of all input fields:

function calcAllFields(id) {
    var id = $(id).attr("id");
    $('#target1').text($("#total" + id).map(function() {
        var currentValue = parseFloat(document.getElementById("currentTotal").value);
        var newValue = parseFloat($("#total" + id).text());
        var newTotal = currentValue + newValue;
        document.getElementById("currentTotal").value = newTotal;
        return newTotal;
        }).get().join());
}

The variable currentTotal is getting its value from a hidden field on my form:

<input type="hidden" id="currentTotal" value="0">

As I enter numbers a field the calculation for that line will be accurate, but the grand total will be inaccurate because the value for currentTotal will continue to increment with every key stroke I make in the input field. Any ideas on how to avoid this from happening?

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about jQuery