Creating a remove and add button in JavaScript for a cart

Viewed 84

I'm working on a project to create a shopping cart in a beginners JavaScript course. So far I've managed to add items to a cart and multiply their value to a subtotal. Where I'm failing is that my + and - aren't working, so I cannot add an idem twice? I get the

Uncaught TypeError: cannot set property 'innerHTML' of null

And I have read that To recap, this error occurs commonly when you try to modify an HTML element that has not appeared yet on the page. The solution is to move your JavaScript code from the head tag below the HTML element.

New to web-development... anyways below is my code.

const products = [{
    "id": 1,
    "name": "Aloe Vera",
    "origin": "Nederländerna",
    "description": "Lättskött suckulent med tjocka gröna blad. En av världens äldsta läkeväxter",
    "height": "Höjd: 120cm",
    "care": "Lättskött suckulent som trivs ljust, men undvik direkt solljus.",
    "image": "img/alovera.jpeg",
    "price": 100
  },
  {
    "id": 2,
    "name": "Citronfikus",
    "origin": "Danmark",
    "description": "En vacker växt med blanka, små gröna blad.",
    "height": "Höjd: 50cm",
    "care": "Passar bra i uterummet sommartid.",
    "image": "img/citronfikus.jpeg",
    "price": 150
  },
  {
    "id": 3,
    "name": "Hampa",
    "origin": "Jamaica",
    "description": "En fin växt med väldigt vackra blad med magiska egenskaper.",
    "height": "Höjd: 50-100cm",
    "care": "Passar bra i uterummet sommartid, vänt mot öst eller väst.",
    "image": "img/hemp.jpg",
    "price": 200
  }
];

/* This section her renders all the items I've added to the cart, it also uses the id's that my objects have saved in the array that I created. I try to generate this button when rendering an item but it doesn't change the amount of items... I don't know why */
function renderCartItems() {
  cartItemsEl.innerHTML = ""; // clear cart element
  cart.forEach((item) => {
    cartItemsEl.innerHTML += `
        <div class="cart-item">
            <div class="item-info" onclick="removeItemFromCart(${item.id})">
                <img src="${item.image}" alt="${item.name}">
                <h4>${item.name}</h4>
            </div>
            <div class="unit-price">
                ${item.price}:-
            </div>
            <div class="units">
                <div class="btn minus" onclick="changeNumberOfUnits('minus', ${item.id})">-</div>
                <div class="number">${item.numberOfUnits}</div>
                <div class="btn plus" onclick="changeNumberOfUnits('plus', ${item.id})">+</div>           
            </div>
        </div>
      `;
  });
}

/* this section creates a function that is supposed to update the numberOfUnits with the - and + buttons that are generated from the code above. But when I press them nothing happens, it doesn't change the number of units and is never updated...*/

function changeNumberOfUnits(action, id) {
  cart = cart.map((item) => {
    let numberOfUnits = item.numberOfUnits;

    if (item.id === id) {
      if (action === "minus" && numberOfUnits > 1) {
        numberOfUnits--;
      } else if (action === "plus" && numberOfUnits < 1) {
        numberOfUnits++;
      }
    }

    return {
      ...item,
      numberOfUnits,
    };
  });

  updateCart();
}
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.5.0/font/bootstrap-icons.css">

<div class="app-container">
  <div class="app-bg">
    <div class="left-side"></div>
    <div class="right-side"></div>
  </div>
  <header>
  </header>
  <div class="products-list">
    <div class="products">
      <!-- render porducts here -->
    </div>
    <div class="cart">
      <div class="cart-header">
        <div class="column1">Vara</div>
        <div class="column2">Pris</div>
        <div class="column3">Antal</div>
      </div>
      <div class="cart-items">
        <!-- render cart items here -->
      </div>
      <div class="cart-footer">
        <div class="subtotal">
          Totalt (0 varor): 0
        </div>
        <div class="checkout">
          Vidare till betalning
        </div>
      </div>
    </div>
  </div>

1 Answers

Oh man so annoying! But I found the solution, in order to be able to increase the amount of items in the cart I have to check if the value is > or < then the actual number added so I solved it like this.

// change number of units for an item
function changeNumberOfUnits(action, id) {
  cart = cart.map((item) => {
    let numberOfUnits = item.numberOfUnits;

    if (item.id === id) {
      if (action === 'minus' && numberOfUnits >= numberOfUnits) {
        numberOfUnits--;
      } else if (action === 'plus' && numberOfUnits <= numberOfUnits) {
        numberOfUnits++;
      }
    }
    return {
      ...item,
      numberOfUnits,
    };
  });
  updateCart();

Related