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:

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

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:

  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.

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>
Advertisement