Mousa Saleh Mousa Saleh - 7 months ago 41
HTML Question

How to sum divs values?

I have some divs that have values. I want to sum in one


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">

<div class="cash-out">



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

You can see
in this code:

return "<div id='cart-list'><div class='product-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>";

Answer Source

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=""></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 id="cash-out">0</div>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download