[jquery] jQuery calculate sum of values in all text fields

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()
   })
});

This question is related to jquery

The answer is


A tad more generic copy/paste function for your project.

sumjq = function(selector) {
    var sum = 0;
    $(selector).each(function() {
        sum += Number($(this).text());
    });
    return sum;
}

console.log(sumjq('.price'));

$(".price").each(function(){ 
total_price += parseFloat($(this).val()); 
}); 

please try like this...


If you don't need to support IE8 then you can use the native Javascript Array.prototype.reduce() method. You will need to convert your JQuery object into an array first:

 var sum = $('.price').toArray().reduce(function(sum,element) {
     if(isNaN(sum)) sum = 0;
     return sum + Number(element.value);
 }, 0);

Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce


Use this function:

$(".price").each(function(){
total_price += parseInt($(this).val());
});

$('.price').blur(function () {
    var sum = 0;
    $('.price').each(function() {

        if($(this).val()!="")
         {
            sum += parseFloat($(this).val());
         }

    });
        alert(sum);
});?????????

JS Fiddle


This should fix it:

var total = 0;   
$(".price").each( function(){
          total += $(this).val() * 1;
});

This will work 100%:

<script type="text/javascript">  
  function calculate() {
    var result = document.getElementById('result');
    var el, i = 0, total = 0; 
    while(el = document.getElementById('v'+(i++)) ) {
      el.value = el.value.replace(/\\D/,"");
      total = total + Number(el.value);
    }
    result.value = total;
    if(document.getElementById('v0').value =="" &&
      document.getElementById('v1').value =="" &&
      document.getElementById('v2').value =="" ) {
        result.value ="";
      }
    }
  }
</script>
Some number:<input type="text" id ="v0" onkeyup="calculate()">
Some number:<input type="text" id ="v1" onkeyup="calculate()">
Some number:<input type="text" id ="v2" onkeyup="calculate()">
Result: <input type="text" id="result" onkeyup="calculate()"  readonly>

Similarly along the lines of these answers written as a plugin:

$.fn.sum = function () {
    var sum = 0;
    this.each(function () {
        sum += 1*($(this).val());
    });
    return sum;
};

For the record 1 * x is faster than Number(x) in Chrome