JQuery: form to calculate total of input fields... but several instances of this form on the same page

nadir picture nadir · Aug 5, 2012 · Viewed 16.5k times · Source

I've spent more than 20 hours on Stackoverlfow to find a solution to my problem (trying to combine different solutions), but I'm still stuck and definitely need your help!

Basically, I have a simple form with 3 "amount" input fields, and a "total amount" field (sum of the 3 amounts).

Here is the HTML code:

<table border="1">

    <tr>
        <td>Amount 1</td>
        <td><input class="amount" type="text"/></td>
    </tr>

     <tr>
        <td>Amount 2</td>
        <td><input class="amount" type="text"/></td>
    </tr>

    <tr>
        <td>Amount 3</td>
        <td><input class="amount" type="text"/></td>
    </tr>

    <tr>
        <td>Total Amount</td>
        <td><span class="total">0</span></td>
    </tr>

</table>

Then the working JQuery code:

$(document).ready(function(){           
        $('input').each(function() {
            $(this).keyup(function(){   
                calculateTotal();
            });
        });
    });

    function calculateTotal() {
        var sum = 0;
        $('input').each(function() {
            if(!isNaN(this.value) && this.value.length!=0) {
                sum += parseFloat(this.value);
            }
        });

        $(".total").html(sum.toFixed(2));
    }

However I want to use several instances of the same form within the same page, and I'm trying to have only one "general" JQuery function like my current one, that could work for any form, even on the same page, without mixing fields between forms.

Basically, a function that says "each time an input field is updated, recalculate the total amount and put it in the total field of the CURRENT form/table"

I tried different ways, especially by surrounding the table with <div> then find it through "currentdiv = $(this).prev("div");" then loop through "current div" using the each function. But each time either the code is not working, or the total field adds-up amounts from other forms! I also tried something like the following, without using <div>:

$(this).closest('tr').next().find('span.total').html(sum.toFixed(2));
or
$(this).closest('span.total').html(sum.toFixed(2));
or even
$(this).closest('span').prevAll('.total:first').html(sum.toFixed(2));

Thanks in advance for your help!

Answer

Kiruse picture Kiruse · Aug 5, 2012

A little overhaul of your code in general. jQuery does not require you to iterate through all the matched elements in order to attach a listener to them. This is just enough:

$(document).ready(function(){           
    $('input.amount').keyup(function(){   
        calculateTotal(this);
    });
});

function calculateTotal( src ) {
    var sum = 0,
        tbl = $(src).closest('table');
    tbl.find('input.amount').each(function( index, elem ) {
        var val = parseFloat($(elem).val());
        if( !isNaN( val ) ) {
            sum += val;
        }
    });
    tbl.find('input.total').html(sum.toFixed(2));
}

Note that the this keyword in an event handler is not jQuery-wrapped, AFAIK, just as the elem parameter of an .each handler.