How to set up adding to cart?

  • 0
    There is an array of objects displayed in HTML, each click is added to the cart, how to make sure that an existing item is not added to the cart again? And how do you make the emptying basket button full?
    spoiler
    const goods = [
    {
    name: "car 1",
    price: 100
    },
    {
    name: "car 2",
    price: 200
    },
    {
    name: "car 3",
    price: 300
    }
    ]

    const goodsInStorage = JSON.parse (localStorage.getItem ("goods"));
    const goodsInCart = goodsInStorage? goodsInStorage: [];

    const store = document.querySelector (". root");
    const cart = document.querySelector (". cart");

    const addItemFromStorage = () = & gt; {
    goodsInCart.forEach ((item) = & gt; {
    const goodInCart = document.createElement ("div")
    goodInCart.innerText = `Brand $ {item.name}, price $ {item.price}`;
    cart.append (goodInCart)

    })
    }

    const goodClicklHandler = (item) = & gt; {
    item.addEventListener ("click", function () {
    cart.innerHTML = ""
    const itemIndex = this.getAttribute ("data-good-id")
    goodsInCart.push (goods [itemIndex])

    localStorage.setItem ("goods", JSON.stringify (goodsInCart))

    addItemFromStorage ()
    })
    }

    goods.forEach ((good, index) = & gt; {
    const item = document.createElement ("div");
    item.dataset.goodId = index;
    item.innerText = `Brand $ {good.name}, price $ {good.price}`;
    store.append (item);

    goodClicklHandler (item);
    });

    addItemFromStorage ()

    JavaScript Anonymous, Jun 6, 2019

  • 1 Answers
  • 0
    1. When adding to the cart, check if this item is in the cart (You will have the id of the goods in the real application, check by them. In principle, only the id of the goods is added to the cart)

    2. Buttons add to cart should no longer be in the product card if it is in the cart. In its place, you can insert a selection of the quantity of goods (with min and max values, by entering manually and + -), and also add a delete button if the marketing department does not mind (you can delete with a choice of less than 1)

    3. Emptying the trash = assigning an empty array. You can remove like this

    4. It is better to write something like this on frameworks, since without them, you will have to control the interface re-rendering with handles. At the very least, it's worth describing it through a class.
    Brielle Cordova

Your Answer
To place the code, please use CodePen or similar tool. Thanks you!