Hey everyone I’m trying to do a very simple calculation using javascript to find a running total. I seem to be missing something. I did look through SO and found some very similar scenarios but, I can’t seem to relate to my own code.
Here is the script I am using to calc my running total.
var total = 0;
function GetTotal(txtBox) {
total += parseInt(txtBox.value) || 0;
$("#chkTotal").html(total);
}
and here is some code from my view:
<div class="editor-field">
@Html.TextBox("FirstDemo", String.Empty, new { id = "firstdemo", onchange = "GetTotal(this)" })
@Html.ValidationMessageFor(model => model.FirstDemo)
</div>
<div>
<h3>Total Checked</h3>
</div>
<div id="chkTotal"></div>
The total calculates perfectly, until a value is changed in a text box, in which case whatever has been entered in the textbox is added again to the running total.
Can anyone help me?
The problem is the global scope of your
totalvariable: I imagine you have several text fields in the form where you set them up to handle theonchageevent the same way. The first time you enter something, the value is added correctly to total but the moment you change something in any of the text fields, it adds again the new value. Again, becausetotalhas global scope.You should really move
totallocally inside the function and re-parse all values in the input elements you are interested in.Since you are using jquery, you could do something like this instead:
Here’s a jsfiddle demonstrating it for you.