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:
var products = [ { "name": "Aloe Vera", "image": "bilder/severin-candrian-dgvFsLfIX9E-unsplash.jpg", "origin": "NederlĂ€nderna", "description": "LĂ€ttskött suckulent med tjocka gröna blad. En av vĂ€rldens Ă€ldsta lĂ€kevĂ€xkter. Trivs pĂ„ soliga platser. LĂ„t den torka ut mellan varje vattning.", "height": "120cm", "care": "Trivs ljust, men undvik direkt solljus. Vattna undertill och inte pĂ„ vĂ€xten, men lĂ„t jorden torka mellan varje vattning. Ge flytande nĂ€ring frĂ„n vĂ„r till höst. Eventuell omplantering ska göras pĂ„ vĂ„ren.", "price": 59 }, { "name": "Marmorblad", "image": "bilder/severin-candrian-8nONCr6eTeg-unsplash.jpg", "origin": "Brasilien", "description": "Fin och spĂ€nnande vĂ€xt med kontrastrika blad med grönt mönster och lila undersida pĂ„ bladen. Denna dekorativa planta passar perfekt i en kruka pĂ„ golvet eller pĂ„ en piedestal eller ett sidobord.", "height": "65cm", "care": "Ge den lite utrymme sĂ„ att bladen kan strĂ€cka ut sig vĂ€l bĂ„de uppĂ„t och Ă„t sidorna och skapa en grön och harmonisk atmosfĂ€r i hemmet. Trivs i ljus och halvskugga, undvik direkt solljus. HĂ„ll jorden lĂ€tt fuktig. Gillar att bli duschad pĂ„ bladen.", "price": 299 }, { "name": "Lyktranka", "image": "bilder/severin-candrian-xGpYDi-0348-unsplash.jpg", "origin": "Sydafrika, Swaziland och Zimbabwe", "description": "Ăven kĂ€nd som HjĂ€rtan pĂ„ trĂ„d. Lyktrankan Ă€r mycket lĂ€tt att sköta och Ă€r en vacker hĂ€ngvĂ€xt med smĂ„ mörkgröna hjĂ€rtformade blad med ett silverskimrande mönster. Plantan kan bli över en meter, vilket gör den vĂ€l lĂ€mpad som hĂ€ngvĂ€xt eller i en hög kruka.", "height": "15 cm", "care": "Trivs ljust, undvik direkt solljus. LĂ„t den torka lĂ€tt mellan vattningarna.", "price": 79 } ]; let cart = {} ; function initCart() { for (let product of products) { cart[product.name] = 0; } } function renderCart() { let tbody = document.querySelector("#cart > tbody"); tbody.innerHTML = ""; for (let product of products) { let row = tbody.insertRow(-1); let cellName = row.insertCell(-1); let cellAmount = row.insertCell(-1); let cellPrice = row.insertCell(-1); let amount = cart[product.name]; cellName.textContent = product.name; cellAmount.textContent = amount; cellPrice.textContent = amount * product.price; } } function increment(name) { console.log("Name: " + name); cart[name]++; renderCart(); } function buy() { document.getElementById("totalCart").textContent = "Du har lagt till " + count + " st" + " produkter." + " " + "Vilket blir en summa pĂ„ " + total + " kr" + "." ; } var count = countCart() ; var total = totalCart() ; function countCart() { var totalCount = 0 ; for (var i in cart) { totalCount += cart[i].amount ; } return totalCount ; } function totalCart() { var totalPrice = 0 ; for (var i in cart) { totalPrice += cart[i].price ; } return totalPrice ; } function renderProducts() { const template = ` <img> <div class="p-template"> <div> <span class="name"></span> </div> <div class="origin"></div> <div class="height"></div> <div class="care"></div> <div class="description"></div> <div class="price"></div> <div> <input class="button" value="LĂ€gg i varukorg" type="button"/> </div> </div> `; const container = document.querySelector("#products"); for (let product of products) { let item = document.createElement("div"); item.classList.add("item", "ml-2"); item.innerHTML = template; item.querySelector("img").src = product.image; item.querySelector(".name").textContent = product.name; item.querySelector(".origin").textContent = product.origin; item.querySelector(".height").textContent = product.height; item.querySelector(".care").textContent = product.care; item.querySelector(".description").textContent = product.description; item.querySelector(".price").textContent = product.price; item.querySelector(".button").addEventListener("click", () => increment(product.name)); container.appendChild(item); } } window.onload = function() { renderProducts(); initCart(); renderCart(); }
And my html:
<body> <h1>Varukorg</h1> <div class="container"> <div class="row"> <table class="table" id="cart"> <thead> <tr> <th>Produkt</th> <th>Antal</th> <th>Pris</th> </tr> </thead> <tbody id="table-body"></tbody> </table> <form> <input class="buy-btn" onclick="buy()" value="Köp" type="button"/> </form> <p id="totalCart"></p> <h2>VÀxter</h2> <div class="" id="products"></div> </div> </div> </body> <script src="inlamning2.js"></script>
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:
function buy() { var count = Object.values(cart).reduce((sum, cur) => sum += cur, 0); var total = Object.entries(cart).reduce((sum, cur) => { const [product, quantity] = cur; return sum += products.find(p => p.name === product).price * quantity; }, 0); document.getElementById("totalCart").textContent = "Du har lagt till " + count + " st" + " produkter." + " " + "Vilket blir en summa pÄ " + total + " kr" + "."; }
Explanation of the code:
count
is pretty straight forward: you get all the values in yourcart
object and sum them up usingArray.prototype.reduce
total
is a bit complicated: you need to iterate through yourcart
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 theproducts
array of object to retrieve the price for a given product, and multiplying the quantity.
var products = [{ "name": "Aloe Vera", "image": "bilder/severin-candrian-dgvFsLfIX9E-unsplash.jpg", "origin": "NederlĂ€nderna", "description": "LĂ€ttskött suckulent med tjocka gröna blad. En av vĂ€rldens Ă€ldsta lĂ€kevĂ€xkter. Trivs pĂ„ soliga platser. LĂ„t den torka ut mellan varje vattning.", "height": "120cm", "care": "Trivs ljust, men undvik direkt solljus. Vattna undertill och inte pĂ„ vĂ€xten, men lĂ„t jorden torka mellan varje vattning. Ge flytande nĂ€ring frĂ„n vĂ„r till höst. Eventuell omplantering ska göras pĂ„ vĂ„ren.", "price": 59 }, { "name": "Marmorblad", "image": "bilder/severin-candrian-8nONCr6eTeg-unsplash.jpg", "origin": "Brasilien", "description": "Fin och spĂ€nnande vĂ€xt med kontrastrika blad med grönt mönster och lila undersida pĂ„ bladen. Denna dekorativa planta passar perfekt i en kruka pĂ„ golvet eller pĂ„ en piedestal eller ett sidobord.", "height": "65cm", "care": "Ge den lite utrymme sĂ„ att bladen kan strĂ€cka ut sig vĂ€l bĂ„de uppĂ„t och Ă„t sidorna och skapa en grön och harmonisk atmosfĂ€r i hemmet. Trivs i ljus och halvskugga, undvik direkt solljus. HĂ„ll jorden lĂ€tt fuktig. Gillar att bli duschad pĂ„ bladen.", "price": 299 }, { "name": "Lyktranka", "image": "bilder/severin-candrian-xGpYDi-0348-unsplash.jpg", "origin": "Sydafrika, Swaziland och Zimbabwe", "description": "Ăven kĂ€nd som HjĂ€rtan pĂ„ trĂ„d. Lyktrankan Ă€r mycket lĂ€tt att sköta och Ă€r en vacker hĂ€ngvĂ€xt med smĂ„ mörkgröna hjĂ€rtformade blad med ett silverskimrande mönster. Plantan kan bli över en meter, vilket gör den vĂ€l lĂ€mpad som hĂ€ngvĂ€xt eller i en hög kruka.", "height": "15 cm", "care": "Trivs ljust, undvik direkt solljus. LĂ„t den torka lĂ€tt mellan vattningarna.", "price": 79 } ]; let cart = {}; function initCart() { for (let product of products) { cart[product.name] = 0; } } function renderCart() { let tbody = document.querySelector("#cart > tbody"); tbody.innerHTML = ""; for (let product of products) { let row = tbody.insertRow(-1); let cellName = row.insertCell(-1); let cellAmount = row.insertCell(-1); let cellPrice = row.insertCell(-1); let amount = cart[product.name]; cellName.textContent = product.name; cellAmount.textContent = amount; cellPrice.textContent = amount * product.price; } } function increment(name) { console.log("Name: " + name); cart[name]++; renderCart(); } function buy() { var count = Object.values(cart).reduce((sum, cur) => sum += cur, 0); var total = Object.entries(cart).reduce((sum, cur) => { const [product, quantity] = cur; return sum += products.find(p => p.name === product).price * quantity; }, 0); document.getElementById("totalCart").textContent = "Du har lagt till " + count + " st" + " produkter." + " " + "Vilket blir en summa pĂ„ " + total + " kr" + "."; } function renderProducts() { const template = ` <img> <div class="p-template"> <div> <span class="name"></span> </div> <div class="origin"></div> <div class="height"></div> <div class="care"></div> <div class="description"></div> <div class="price"></div> <div> <input class="button" value="LĂ€gg i varukorg" type="button"/> </div> </div> `; const container = document.querySelector("#products"); for (let product of products) { let item = document.createElement("div"); item.classList.add("item", "ml-2"); item.innerHTML = template; item.querySelector("img").src = product.image; item.querySelector(".name").textContent = product.name; item.querySelector(".origin").textContent = product.origin; item.querySelector(".height").textContent = product.height; item.querySelector(".care").textContent = product.care; item.querySelector(".description").textContent = product.description; item.querySelector(".price").textContent = product.price; item.querySelector(".button").addEventListener("click", () => increment(product.name)); container.appendChild(item); } } window.onload = function() { renderProducts(); initCart(); renderCart(); }
<h1>Varukorg</h1> <div class="container"> <div class="row"> <table class="table" id="cart"> <thead> <tr> <th>Produkt</th> <th>Antal</th> <th>Pris</th> </tr> </thead> <tbody id="table-body"></tbody> </table> <form> <input class="buy-btn" onclick="buy()" value="Köp" type="button" /> </form> <p id="totalCart"></p> <h2>VÀxter</h2> <div class="" id="products"></div> </div> </div>