jQuery multiple running totals

Posted by Benjamin Randal on Stack Overflow See other posts from Stack Overflow or by Benjamin Randal
Published on 2012-11-18T22:51:24Z Indexed on 2012/11/18 23:00 UTC
Read the original article Hit count: 348

Filed under:
|

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>

© Stack Overflow or respective owner

Related posts about jQuery

Related posts about asp.net-mvc-3