0

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>";
   });
Mousa Saleh
  • 42
  • 1
  • 10

1 Answers1

1

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>
AGE
  • 3,752
  • 3
  • 38
  • 60
  • But I want to sum `item-total` – Mousa Saleh Aug 18 '17 at 19:57
  • How many `item-total` do you have? Do you want to sum `item-total` into something else or with each other? – AGE Aug 18 '17 at 19:59
  • it is a cart and maybe there is more every time – Mousa Saleh Aug 18 '17 at 20:00
  • then do **not** use an `id='item-total'`, instead use `class='item-total'`. Please understand the difference between using **id** and **class** – AGE Aug 18 '17 at 20:01
  • I have did it and same value I got – Mousa Saleh Aug 18 '17 at 20:03
  • @MousaSaleh I got busy for a while, I updated my answer with a JSFiddle. I changed the `

    ` for `
    ` instead, it makes more sense in HTML and you should set the style of the `.item` using CSS as these do not represent **headings** :)

    – AGE Aug 18 '17 at 20:39