Kosmos Web Design
Kosmos Web Design

Reputation: 103

How do I add up the values of multiple divs in jQuery and append the final sum to another div?

My markup looks like this:

<div class="container">
<div class="box">
    <div class="box_content">
        <div class="box_price">180</div>
    </div>
</div>
<div class="box">
    <div class="box_content">
        <div class="box_price">230</div>
    </div>
</div>
<div class="box">
    <div class="box_content">
        <div class="box_price">120</div>
    </div>
</div>
</div>
<div class="cost"></div>

The number of boxes is not static and their price can be any value. How do I use jQuery to make the div "cost" display the sum of all "box_price" divs?

Upvotes: 0

Views: 983

Answers (3)

Sudhanshu Saxena
Sudhanshu Saxena

Reputation: 1199

Use each() iterator for traverse through every element.

Here is the fiddle

Fiddle

Upvotes: 0

Kinshuk Lahiri
Kinshuk Lahiri

Reputation: 1500

Try this:

var sum = 0;

$(".box_price").each(function(){

    sum += parseInt($(this).html());

});

$('#cost').html(sum);

Upvotes: 0

Mohit Tanwani
Mohit Tanwani

Reputation: 6628

Use each() to iterate through your elements.

var total = 0;
$('.box > .box_content > .box_price').each(function(){
  total += parseInt($(this).text());
});

Append it to the container

$('.container').append("<div class='sum'>Total : "+total+"</div>");

var total =0;
$('.box > .box_content > .box_price').each(function(){
  total += parseInt($(this).text());
});
$('.container').append("<div class='sum'>Total : "+total+"</div>");
console.log(total);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<div class="box">
    <div class="box_content">
        <div class="box_price">180</div>
    </div>
</div>
<div class="box">
    <div class="box_content">
        <div class="box_price">230</div>
    </div>
</div>
<div class="box">
    <div class="box_content">
        <div class="box_price">120</div>
    </div>
</div>
</div>

Upvotes: 7

Related Questions