Link to home
Start Free TrialLog in
Avatar of Robert Granlund
Robert GranlundFlag for United States of America

asked on

jQuery function to sum input fields

I have a function that displays the total certain text input fields.  

<script>
 $( window ).load(function() {     
    var sum = 0;
    $(".calculate").each(function(){
        var aValue = $(this).val();
        sum += aValue;
        $(".display-total").html('<strong>Total</strong>&nbsp;<span class="sale_price pull-right"><span class="cart_total">'+ sum + '</span></span>');
    });
});
</script>

Open in new window

The issue is, is that The function ends up printing out each field input (Concatenating them)  instead of adding them all up.
ASKER CERTIFIED SOLUTION
Avatar of Hammadh Abdul Rahman
Hammadh Abdul Rahman
Flag of Maldives image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Robert Granlund

ASKER

No I get 0 as a return; How would I write it to calculate the sum total of numbers contained inside of a div, instead. (not from an input field) The divs are being written to before this function runs.
<html>
<span id="this-display-total-{row_id}" class="calculate"></span>
</html>
<script>
 $( window ).load(function() { 
$("#this-display-total-{row_id}").html( premium_total );
    
    var sum = 0;
    $(".calculate").each(function(){
        var aValue = $(this).val();
        sum += Number(aValue);
        $(".display-total").html('<strong>Total</strong>&nbsp;<span class="sale_price pull-right"><span class="cart_total">'+ sum + '</span></span>');
    });
});
</script>

Open in new window

Also change line 10 to
var aValue = $(this).html();

Open in new window

OK, that worked.
Avatar of nap0leon
nap0leon

@rgranlund - if the solution provided works, please "Accept" it.