javascript – Calculate the sum ul> li

Question:

Good afternoon, guys, tell me what is wrong, you need to calculate the sum of the numbers in the basket.
It should be borne in mind that the value in .price may change.

I have the following code:

 window.onload = function(){
   var sum = 0;
   $('.cart-list li').each(function(){
      sum+=parseInt($('.price', this).text());
   });
    $('#res').html(sum);;
  }

The HTML is as follows:

<li id="cart-'.$row['id'].'">
    <div class="image">
        <span>
            <img src="'.$row['img'].'" alt="'.$row['name'].'" width="87" height="87"></span>
    </div>

    <div class="text-holder"> <strong class="name">'.$row['name'].'</strong>
        <p>'.$row['desc'].'</p>
        <p> <i>'.$row['ingridient'].'</i>
        </p>
    </div>
    <div class="cart-hold">
        <div class="combobox">
            <a class="dec" onclick="minus(\''.$row['id'].'\');">&lt;</a>
            <a class="inc" onclick="plus(\''.$row['id'].'\');">&gt;</a>
            <input type="text" id="input-'.$row['id'].'" value="1" disabled></div>
        <div class="price-box">
            <span class="regular-price">
                <span class="price" id="price-'.$row['id'].'">'.$row['price'].'</span>
                <span style="display:none" id="prices-'.$row['id'].'">'.$row['price'].'</span>
                грн.
            </span>
        </div>
        <a href="#" class="del nh_cart_delete" onclick="delItems(\''.$row['id'].'\');">X</a>
    </div>
</li>

Answer:

Check the contents of the variables. With javascript, you're fine.

Here's your example with a slightly simplified layout:

var sum = 0;
$('.cart-list li').each(function() {
  sum += parseInt($('.price', this).text());
});
$('#res').html(sum);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<ul class="cart-list">
  <li id="cart-1">
    <div class="cart-hold">
      <div class="price-box">
        <span class="regular-price">
                <span class="price" id="price-1">1000</span>
        <span style="display:none" id="prices-1">1000</span> грн.
        </span>
      </div>
    </div>
  </li>
  <li id="cart-2">
    <div class="cart-hold">
      <div class="price-box">
        <span class="regular-price">
                <span class="price" id="price-2">1000</span>
        <span style="display:none" id="prices-2">1000</span> грн.
        </span>
      </div>
    </div>
  </li>
</ul>
<div id="res"></div>
Scroll to Top