tags:

views:

434

answers:

3

I have an order form with about 30 text fields that contain numerical values. I'd like to calculate the sum of all those values on blur.

I know how to select all text fields but not how to loop through them and add up all their values?

$(document).ready(function(){
   $(".price").blur(function() {
    //loop and add up every value from $(".price").val()
   })
});
+5  A: 

$('.price').blur(function () {
    var sum = 0;
    $('.price').each(function() {
        sum += Number($(this).val());
    });

    // here, you have your sum
});​​​​​​​​​
Marko Dumic
A: 
$(".price").each(function(){
total_price += parseInt($(this).val());
});
Deniss Kozlovs
The price is not always integer.
Marko Dumic
I think you'll want `parseFloat()`
alex
A: 

This should fix it:

var total = 0;   
$(".price").each( function(){
          total += $(this).val();
});
Bvandorp
This will concatenate strings returned from .val().
Marko Dumic