Shopping cart total price does not update
Hello, I am creating a shopping cart from this tutorial: https://www.youtube.com/watch?v=YeFzkC2awTM&t=940s but when I add new items the total price counter does not update and I can add two of the same item
This is my code:
https://codepen.io/SuperTesmon/pen/OJaLLWX
Web Dev Simplified
YouTube
JavaScript Shopping Cart Tutorial for Beginners
In this video we will learn how to utilize JavaScript to add functionality to a shopping cart. We will cover how to check if the document is loaded, and how to query the document for elements by class, how to add events to elements. We will then combine all of these techniques to make the shopping cart in our web page work in an intuitive way.
...
2 Replies
In this code you are adding a new table row to the cart and adding the product within this row.
To get the total you are the looping through all the rows and extracting the price of each product.
My first suggestion is that this is not optimal. It would be far simpler to store the total in a variable and simply add the new product price to the variable when it is added.
The issue you have is that you are not adding the “cart-row” class to the added row so when you updateTotal() function runs it doesn’t include the new ones as it is only looking at rows with this class name.
As regards checking if the product is already in the cart, again you are looping through all the cart items and attempting to extract their title from the element with the class name “cart-title” however you don’t use that class name in the code, neither in the initial card contents nor in the items added via JavaScript.
As an aside, you should look in to using arrays and objects to store the cart data as they would make things a lot simpler and require less code.
I have removed some comments as I have just remembered that you are getting this form a tutorial… so you are just following what they do there.
I actually don't look into the tutorial I just took the source code from this tutorial and wrote myself form scratch, that way I understand the code better
Wasn't clear, sorry
I will look into that. thank you very much!