0

I have these divs.

<div class="prices">11.99</div>
<div class="prices">1.99</div>
<div id="price">99</div>

How can I add all the numbers from the divs?

The final result must be 11.99+1.99+99=112.98

Thank you.

3
  • What do you mean add? Where? Commented Oct 11, 2014 at 18:47
  • stackoverflow.com/questions/2417553/… possible duplicate Commented Oct 11, 2014 at 18:48
  • 1
    I didn't knew how to start it. I knew that there must be some kind of a loop but didn't knew how to do it. And why all this hate? Geez Commented Oct 11, 2014 at 18:56

4 Answers 4

4

You can do it like this.

var controls = $("div");
var sum = 0;
for (var i = 0; i < controls.length; i++) {
  var ct = parseFloat($(controls[i]).text());
  sum += ct;
}
alert(sum);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="prices">11.99</div>
<div class="prices">1.99</div>
<div id="price">99</div>

Sign up to request clarification or add additional context in comments.

4 Comments

@semprom , cool ,you can also use $("div").each to make it work!
Plus at the end we can use sum.toFixed(2) to make the number 120.98 ( not 120.97999999999999 ).
Yes, but when i ran this in my browser, it directly gave me 120.98 .
It gives me the larger result. Strange. Never mind. I just wanted to tell if someone get the longer result to use toFixed.
2

One possible solution is this:

var sum = 0;
$("div").filter(function () {
    if ($(this).attr("class") == "prices" || $(this).attr("id") == "price") {
        return sum += parseFloat($(this).text());
    }
});
console.log(sum);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="prices">11.99</div>
<div class="prices">1.99</div>
<div id="price">99</div>

Comments

2

If you just want to sum the values from divs with the class of prices or the id of price. You could do something like this:

var p = 0;
$('.prices').each(function() {p += parseFloat($(this).text());})
$('#price').each(function() {p += parseFloat($(this).text());})    
$('#result').text(p);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="prices">11.99</div>
<div class="prices">1.99</div>
<div id="price">99</div>
Result: <div id="result"></div>

Comments

1

Below code works...

jQuery Code

var price = 0;
$('div.prices, div#price').each(function(){ 
    price = price + parseFloat($(this).html());                 
});
alert(price)

http://jsfiddle.net/6uLs92r7/

Comments

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.