Mousa Saleh
Mousa Saleh

Reputation: 38

How to sum divs values?

I have some divs that have values. I want to sum in one <h3> The probem in my code is that I get the last div value and cannot sum the other.

Html code:

<div class="cart-footer">
      <div class="order-tools">
        <h3 id="total">

        </h3>
      </div>
      <div class="cash-out">

      </div>
    </div>

Jquery:

var sum = 0;
$('#item-total').each(function(){
 var val = $.trim($(this).text());
 if (val) {
 val = parseFloat(val.replace(/^\$/, ""));
 sum += !isNaN(val) ? val : 0;
 }
});
$("#total").html(sum + "$");

You can see #item-total in this code:

$(".cart-body").append(function(){
     return "<div id='cart-list'><div class='product-name'>"+personObject.name+"</div><div class='product-tools'><input type='number' data-id='1' value='1' min='1'></input><label id='price'>Price: "+personObject.price+"</label><label data-value='"+personObject.count * personObject.price+"' id='item-total'>"+personObject.count * personObject.price+"</label></div></div>";
   });

Upvotes: 0

Views: 2651

Answers (1)

AGE
AGE

Reputation: 3792

You are dealing with a logic error in your code. What you are doing incorrectly is looping through $('#item-total'). This is wrong because #item-total is selecting a single unique HTML element.

What you want to do is loop through all the elements using a different selector. For example by replacing in your HTML: <h3 id="total"> into <h3 class="total">.

Now in your JQuery, selecting $('.total') would then select all instances of .total tagged HTML elements.

var items = $('.item'),
    cashOut = $('#cash-out'),
    sum = 0;

$.each(items, function(value) {
  // items[value] will contain an HTML element, representing an 'item'.
  var itemValue = parseFloat(items[value].innerHTML);
  sum += !isNaN(itemValue) ? itemValue : 0;
});

cashOut.html('Total: $' + sum);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="cart-footer">
  <div class="order-tools">
    <div class="item">1</div>
    <div class="item">2</div>
    <div class="item">3</div>
    <div class="item">4</div>
  </div>
</div>
<div id="cash-out">0</div>

Upvotes: 1

Related Questions