Skip to content
Advertisement

How can I calculate the total price of products in a cart using JavaScript?

I’m stuck on how to calculate the total amount and total price of my cart in this project. The task is to create a simple (beginners) e-commerce website where a customer should be able to click on a product and add it to their cart (with the name, amount and price displayed of the product, the amount and price should update correctly according to how many times a customer clicks on the button attached to the product).

And I can only use javascript (or html if necessary).

I have the website mostly working. Everything can be added to the cart and the cart keeps track of the amount and price for each product.

But I can’t figure out how to make it so when I press the buy button, below the cart, the total amount and total price of all the products added to the cart is displayed in a string beneath the cart.

I’ve tried searching online for answers but I can’t seem to figure it out.

Please help! 🙂

Anything you can think of is greatly appreciated because at this point I’m completely clueless. And worth to note, I’m really new to javascript!

Here are my javascript code thus far:

JavaScript

And my html:

JavaScript

Sorry some of the words are in Swedish! The only words you probably need to know is:

“lägg i varukorgen” = add to cart

“köp” = buy

“pris” = price

“antal” = amount

“produkt” = product

Advertisement

Answer

Your issue is that your cart is only storing the following information in key-value pairs: the key is the product name, and the quantity is the value. There is no price information in the cart object at all, therefore computing it requires looking up the original products array.

Moreover, count and total are declared outside the buy() function, yet the function, when invoked, does not update these values. These values are only set at runtime and is not updated after.

Therefore the quickest solution is to rewrite your buy() function into something like this, while removing the countCart() and totalCart() functions:

JavaScript

Explanation of the code:

  1. count is pretty straight forward: you get all the values in your cart object and sum them up using Array.prototype.reduce
  2. total is a bit complicated: you need to iterate through your cart in a way that gives you access to with the key (product name) and value (the quantity). Object.entries() can do that for you. Then it is a matter of looking up the products array of object to retrieve the price for a given product, and multiplying the quantity.

JavaScript
JavaScript
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement