• Home
  • Jobs
  • Courses
  • Questions
  • Teachers
  • For business
  • ES/EN

0

30
Views
calculate values inside a for loop

as a newbie in JavaScript. I trying to get the total price of each product.

<div class="product">
  <span class="name">product 1</span>
  <span class="price">25.00</span>
</div>
<div class="product">
  <span class="name">product 2</span>
  <span class="price">45.00</span>  
</div>

<div id="cart-total"></div>

And this is my code... what am i doing wrong?

const products = document.querySelectorAll(".product");
const productName = document.querySelectorAll(".name");
const productPrice = document.querySelectorAll(".price");
const cartTotal = document.querySelector("#cart-total");
let total = 0;

for (i = 0; i < products.length; i++) {
 
  const productPriceValue = parseInt(productPrice[i].innerText);
  total += productPriceValue;
}
console.log(total) // prints 70 where i need it to print 70.00
about 1 month ago ·

Juan Pablo Isaza

1 answers
Answer question

0

Besides converting int to float, you need to define total value above the iteration, it becomes 0 on each element.

about 1 month ago · Juan Pablo Isaza Report
Answer question
Find remote jobs
Loading

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post job Plans Our process Sales
Legal
Terms and conditions Privacy policy
© 2022 PeakU Inc. All Rights Reserved.