Reputation: 429
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?
Upvotes: 0
Views: 623
Reputation: 63962
The problem is the global scope of your total
variable: I imagine you have several text fields in the form where you set them up to handle the onchage
event 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, because total
has global scope.
You should really move total
locally 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:
function GetTotal(txtBox) {
var total = 0;
$('input:text').each(function(index, value) {
total += parseInt($(value).val() || 0);
});
$("#chkTotal").html(total);
}
Here's a jsfiddle demonstrating it for you.
Upvotes: 4
Reputation: 207527
Easiest solution, loop through all the form elements and redo the calculation.
I see jQuery in your code so it is a basic selector that gets the elements and an each loop.
function GetTotal(txtBox) {
var total = 0;
$(".calculationClass").each(
function() {
total += parseInt(this.value,10) || 0;
}
);
$("#chkTotal").html(total);
}
Upvotes: 1