85

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()
   })
});
3
  • 2
    Look at JQuery each function (api.jquery.com/each) Commented Mar 10, 2010 at 14:29
  • 8
    just want to know one thing.Why the above posted questioned person is not asked about the research work he has done. As the posted question doesn't show any research work or what he tried at least, especially when the question is not a very tricky and complex one. The solution for the above question can be Google easily still it has received 22 up votes. No issues on up votes but what about the research work? Is it that members with lesser points on Stack are asked about research work? Commented Aug 29, 2013 at 5:37
  • Possible duplicate of Sum using jQuery each function Commented Oct 12, 2016 at 13:04

9 Answers 9

233

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

    // here, you have your sum
});​​​​​​​​​
Sign up to request clarification or add additional context in comments.

2 Comments

Thx @MarkoDumic but what if i want kinda like subtotals ( qty * price ) then calaculate the grand rotal !
For a slightly more elegant solution you can use Array.prototype.reduce: stackoverflow.com/a/37466639/1988326
30

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

2 Comments

I think you mean .val() and not .text()
@PeterMeth it seems it depends stackoverflow.com/questions/807867/…
15

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

Comments

6

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

Comments

4

Use this function:

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

2 Comments

The price is not always integer.
I think you'll want parseFloat()
2

This should fix it:

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

2 Comments

This will concatenate strings returned from .val().
A suggestion from an Anon User is to use the following: var total = 0; $(".price").each( function(){ total += $(this).val() * 1; });
0
$('.price').blur(function () {
    var sum = 0;
    $('.price').each(function() {

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

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

JS Fiddle

Comments

0

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>

1 Comment

Hi, welcome to Stack Overflow. When answering a question that already has many answers, please be sure to add some additional insight into why the response you're providing is somehow substantive and not simply echoing what's already been vetted by the original poster.
-1
$(".price").each(function(){ 
total_price += parseFloat($(this).val()); 
}); 

please try like this...

3 Comments

I'm not sure you want this: "2 apples" + "3 oranges" => 5
I have an order form with about 30 text fields that contain numerical values.
I'm not sure why you, Marko, would think his method is for anything other than adding values.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.