Search code examples
javascriptjquerysumclassname

sum of values from inputs or strings from paragraphs with same class names always shows '0'


I have a simple shopping cart div in which i have ul list of choosen products. I want to show a sum of price of all products but cant figure it out (li's are created dynamically and can be deleted from the cart so sum should work dynamically too).

This is how the structure of ul looks like:

<ul id='koszyk'>
 <li>
   <input type='hidden' class='price' value='20'>
   <p class='p_price'>20 zł</p>
   <...>
 </li>
</ul>

I have tried to sum by paragraph string using this Sum of values from different divs with the same class , but console output always shows '0':

var sum = 0;
$('.p_price').each(function(){
   sum += parseFloat($(this).text());                                    
});
console.log(sum);

Script is inside ul. I have also tried this, but with same result:

var sum = 0;
$('.price').each(function(){
   sum += parseFloat($(this).valueOf());                                    
});
console.log(sum);

I also tried to use array to store all prices but im not good at operating with arrays. It might be a matter of some simple mistake since im still a beginner so i also prefer a solution as simple as possible.


Solution

  • Use the val() method instead of valueOf() to obtain the value of an input element.

    var sum = 0;
    $('.price').each(function(){
       sum += parseFloat($(this).val());                                    
    });
    console.log(sum);
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <ul id='koszyk'>
     <li>
       <input type='hidden' class='price' value='20'>
       <p class='p_price'>20 zł</p>
       <...>
     </li>
    </ul>