Home > Software engineering >  How to add element to cart from array?
How to add element to cart from array?

Time:12-05

Tell me please, how to add element to cart from array? I got data from json file, after that I displayed products using loop "for in", further I want to add current element to cart (id, name, img, amount), but at this moment I could display in cart only ID of array.

After that a plan to make a counter of elements and button for remove element from cart.

// get data
async function getData() {
    let result = await fetch("https://raw.githubusercontent.com/stn32/store-06/main/db/db.json")
        .then((response) => response.json());
    return result;
}
getData().then((result) => showData(result));



// add to cart
let cart = document.querySelector('.cart .container');
let cartItem = document.createElement('div');

function plus(id) {
    console.log(id);
    cartItem.textContent = id;
    cart.appendChild(cartItem);
}


// show content
function showData(allGoods) {
    let outGoods = '';
    for (let key in allGoods) {
        outGoods  = `
        <div >
            <a><img src="${allGoods[key].image}"/></a>
            <div >
                <p>ID - ${allGoods[key].id}</p>
                <h2>${allGoods[key].name}</h2>
                <p>${allGoods[key].desc}</p>
                <span>${allGoods[key].availability}</span>
                <div >
                    <b>${allGoods[key].price}</b>
                    <div >
                        <button  data-id="${key}">-</button>
                        <button  data-id="${key}" onclick="plus(${key})"> </button>
                    </div>
                </div>
            </div>
        </div>`
    }
    let goodsContent = document.querySelector('.goods .container');
    goodsContent.innerHTML = outGoods;

}
showData();

    
body, div, h1, h2, h3, h4, p, a, b, span, button {
  margin: 0;
  padding: 0;
}

.container {
  max-width: 1000px;
  margin: auto;
}

.goods .container {
  display: flex;
  flex-wrap: wrap;
}
.goods .container .goods__item {
  width: 32%;
  margin-right: 2%;
  margin-bottom: 1rem;
}
.goods .container .goods__item a img {
  width: 100%;
}
.goods .container .goods__item .goods__tx {
  padding: 1rem;
  background: #eee;
}
.goods .container .goods__item .goods__tx p {
  color: #777;
  margin: 5px 0;
  font-size: 0.9rem;
}
.goods .container .goods__item .goods__tx .goods__bottom {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.goods .container .goods__item .goods__tx .goods__bottom .goods__btn {
  display: flex;
}
.goods .container .goods__item .goods__tx .goods__bottom .goods__btn button {
  width: 30px;
  height: 30px;
  margin-left: 0.5rem;
  display: flex;
  justify-content: center;
  align-items: center;
  border-radius: 50%;
  border: none;
  background: #f43737;
  color: #fff;
  cursor: pointer;
}
.goods .container .goods__item:nth-child(3n) {
  margin-right: 0;
}

.cart .container div {
  font-size: 2rem;
}/*# sourceMappingURL=style.css.map */
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="icon" href="img/js.png" sizes="64x64">
    <link rel="stylesheet" href="css/style.css">
    <title>Document</title>
</head>
<body>
    <section >
        <div ></div>
    </section>
    <section >
        <div ></div>
    </section>
    <script src="js/script.js"></script>
</body>
</html>

CodePudding user response:

To add an element to the cart, you will need to create a cart object where you can store the items that the user has added to the cart. This object should have properties for each item in the cart, such as its id, name, image, and quantity.

When the user clicks on the " " button for a particular item, you can retrieve the item's information from the allGoods object using the id that is passed to the plus() function. You can then add a new property to the cart object with the same id, and set its value to an object with the item's name, image, and quantity.

Here is an example of how this could be implemented:

// add to cart
let cart = {};

function plus(id) {
  // Retrieve the item from the allGoods object using the id
  let item = allGoods[id];
  
  // Check if the item is already in the cart
  if (cart[id]) {
    // If it is, increment the quantity
    cart[id].quantity  ;
  } else {
    // If it is not, add the item to the cart
    cart[id] = {
      name: item.name,
      image: item.image,
      quantity: 1
    };
  }

  // Update the cart display
  updateCartDisplay();
}

function updateCartDisplay() {
  // Clear the existing cart items
  cart.innerHTML = "";

  // Loop through the items in the cart object
  for (let id in cart) {
    // Create a div element for the cart item
    let cartItem = document.createElement('div');

    // Set the cart item's content to the item's name and quantity
    cartItem.innerHTML = `${cart[id].name} (${cart[id].quantity})`;

    // Append the cart item to the cart
    cart.appendChild(cartItem);
  }
}

You can then use this cart object to keep track of the items in the cart and display them on the page. You can also add a counter for the number of items in the cart, and a "-" button for each item to allow the user to remove items from the cart.

  • Related