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()
   })
});
stef
  • 26,771
  • 31
  • 105
  • 143
  • 2
    Look at JQuery each function (http://api.jquery.com/each/) – Lazarus Mar 10 '10 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? – Sam M Aug 29 '13 at 05:37
  • Possible duplicate of [Sum using jQuery each function](http://stackoverflow.com/questions/4377410/sum-using-jquery-each-function) – KyleMit Oct 12 '16 at 13:04

9 Answers9

230

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

    // here, you have your sum
});​​​​​​​​​
Marko Dumic
  • 9,848
  • 4
  • 29
  • 33
  • Thx @MarkoDumic but what if i want kinda like subtotals ( qty * price ) then calaculate the grand rotal ! – mercury Mar 09 '16 at 19:44
  • For a slightly more elegant solution you can use Array.prototype.reduce: http://stackoverflow.com/a/37466639/1988326 – mark.monteiro May 27 '16 at 20:20
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'));
ubershmekel
  • 11,864
  • 10
  • 72
  • 89
14

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

Tschallacka
  • 27,901
  • 14
  • 88
  • 133
mark.monteiro
  • 2,609
  • 2
  • 33
  • 38
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

Bron Davies
  • 5,930
  • 3
  • 30
  • 41
4

Use this function:

$(".price").each(function(){
total_price += parseInt($(this).val());
});
Somnath Muluk
  • 55,015
  • 38
  • 216
  • 226
Deniss Kozlovs
  • 4,761
  • 2
  • 28
  • 35
2

This should fix it:

var total = 0;   
$(".price").each( function(){
          total += $(this).val() * 1;
});
BryanH
  • 5,826
  • 3
  • 34
  • 47
Bvandorp
  • 31
  • 1
0
$('.price').blur(function () {
    var sum = 0;
    $('.price').each(function() {

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

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

JS Fiddle

Sadikhasan
  • 18,365
  • 21
  • 80
  • 122
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>
smonff
  • 3,399
  • 3
  • 36
  • 46
  • 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. – chb Jan 26 '19 at 20:26
-1
$(".price").each(function(){ 
total_price += parseFloat($(this).val()); 
}); 

please try like this...

CMMaung
  • 165
  • 5
  • 11
  • 27