jQuery calculate sum of values in all text fields

Jquery

Jquery Problem Overview


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

Jquery Solutions


Solution 1 - Jquery

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

    // here, you have your sum
});​​​​​​​​​

Solution 2 - Jquery

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'));

Solution 3 - Jquery

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

Solution 4 - Jquery

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

Solution 5 - Jquery

Use this function:

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

Solution 6 - Jquery

This should fix it:

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

Solution 7 - Jquery

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

please try like this...

Solution 8 - Jquery

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

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

    });
        alert(sum);
});​​​​​​​​​

[JS Fiddle][1] [1]:http://jsfiddle.net/avarm26a/1/

Solution 9 - Jquery

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>

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionstefView Question on Stackoverflow
Solution 1 - JqueryMarko DumicView Answer on Stackoverflow
Solution 2 - JqueryubershmekelView Answer on Stackoverflow
Solution 3 - Jquerymark.monteiroView Answer on Stackoverflow
Solution 4 - JqueryBron DaviesView Answer on Stackoverflow
Solution 5 - JqueryDeniss KozlovsView Answer on Stackoverflow
Solution 6 - JqueryBvandorpView Answer on Stackoverflow
Solution 7 - JqueryCMMaungView Answer on Stackoverflow
Solution 8 - JquerySadikhasanView Answer on Stackoverflow
Solution 9 - JquerybajcepsmeView Answer on Stackoverflow