0I am using jQuery to calculate a running total on multiple textboxes. Just found an awesome response on how to get that working a few days ago, but now I am running into another problem. When using one selector, the total for GetTotal is calculated perfectly. However, when I include the second selector, the totals begin to conflict with one another, and no longer calculate properly. I have been searching for a solution to this for some time now, does anyone have any ideas?
Here is the selector i am currently using:
function GetTotal(txtBox) {
var total = 0;
$('input:text').each(function(index, value) {
total += parseInt($(value).val() || 0);
});
$("#chkTotal").html(total);
}
My view uses these txt boxes
<div class="editor-field">
@Html.TextBox("Field1", String.Empty, new {InputType = "text", id = "field1", onchange = "GetTotal(this)" })
</div>
<div class="editor-field">
@Html.TextBox("Field2", String.Empty, new {InputType = "text", id = "field2", onchange = "GetTotal(this)" })
</div>
<div>
<h3>Total Checked</h3>
</div>
<div id="chkTotal"></div>
Now I am trying to implement another selector which will total two additional editor fields...
function GetTotal1(txtBox) {
var total1 = 0;
$('input:text').each(function (index, value) {
total1 += parseInt($(value).val() || 0);
});
$("#disTotal").html(total1);
}
View:
<div class="editor-field">
@Html.TextBox("Field3", String.Empty, new {InputType = "text", id = "field3", onchange = "GetTotal1(this)" })
</div>
<div class="editor-field">
@Html.TextBox("Field4", String.Empty, new {InputType = "text", id = "field4", onchange = "GetTotal1(this)" })
</div>
<div>
<h3>Total Distributed</h3>
</div>
<div id="disTotal"></div>
Use different HTML classes on the two sums, like
Javascript:
Your each() function runs all input fields no matter if you defined two different functions...
get ALL 4 input fields in both functions.
One approach is to set a class for each surrounding div ie:
And then in your function have
An even more useful approach would be to use the function parameter to pass the class:
You would need to rename the total divs for each group:
Then change "this" in your onChange handlers to each group you want to summarize. (group1, group2 and so on...)