Back

Technologies:

javascriptjavascript
htmlhtml
csscss
avatar
Tolerim
a month ago

Can someone assist me in being redirected to the cart page with selected product details by clicking "add to cart"?

The given text is a request for assistance regarding an e-commerce project utilizing JavaScript. The author presents an HTML code with an add to cart feature and seeks to update the cart with the relevant product information and calculate a total price dynamically. The author attempted to execute the task but the code did not work as anticipated. Assistance is requested to achieve the desired outcome.
Answers(2)
avatar
Vogi
a month ago
Verified Answer
I understand that you are having trouble with the add to cart feature in your e-commerce project. There are many ways to implement this feature in JavaScript. One way is to use the localStorage object to store the cart data and update it dynamically as the user adds or removes items from the cart. Here is an example of how you can implement this feature:
// Get the add to cart button element
const addToCartButton = document.querySelector('.add-to-cart');

// Add an event listener to the button
addToCartButton.addEventListener('click', () => {
  // Get the product information from the HTML code
  const productName = document.querySelector('.product-name').textContent;
  const productPrice = document.querySelector('.product-price').textContent;

  // Get the cart data from localStorage
  let cartData = JSON.parse(localStorage.getItem('cart')) || [];

  // Check if the product is already in the cart
  let productIndex = -1;
  for (let i = 0; i < cartData.length; i++) {
    if (cartData[i].name === productName) {
      productIndex = i;
      break;
    }
  }

  // If the product is already in the cart, update its quantity
  if (productIndex !== -1) {
    cartData[productIndex].quantity++;
  } else {
    // Otherwise, add the product to the cart
    const newProduct = {
      name: productName,
      price: productPrice,
      quantity: 1,
    };
    cartData.push(newProduct);
  }

  // Save the updated cart data to localStorage
  localStorage.setItem('cart', JSON.stringify(cartData));

  // Update the cart total price dynamically
  let totalPrice = 0;
  for (let i = 0; i < cartData.length; i++) {
    totalPrice += parseFloat(cartData[i].price) * cartData[i].quantity;
  }
  document.querySelector('.cart-total-price').textContent = totalPrice.toFixed(2);
});
This code listens for a click event on an add to cart button element and retrieves the product information from the HTML code. It then checks if the product is already in the cart and updates its quantity if it is. If not, it adds the product to the cart. Finally, it saves the updated cart data to localStorage and updates the total price of the cart dynamically. I hope this helps! Let me know if you have any further questions.

Sources

Cart.js — A Javascript library to power your Shopify theme's cart.Use addToCart () function from sn_sc.CartJS () to add multiple items ...Add to Cart Interaction in CSS and JavaScript | CodyHouse25+ Best JavaScript Shopping Cart Examples with DemoDynamically update cart totals using JS and HTML?Adding a item into a cart automatically using javascript
avatar
Tolerim
a month ago
The code you have shared only captures the product details when the "add to cart" button is clicked, but it doesn't do anything with the data. To achieve what you want, you need to create a cart object that you can manipulate and update whenever a product is added, removed, or the quantity changes. Here is an example implementation of a cart object:
// create a cart object
const cart = {
  items: [],
  addItem: function(item) {
    // check if item is already in the cart
    const index = this.items.findIndex(i => i.id === item.id);
    if (index !== -1) {
      // if item exists, update the quantity
      this.items[index].quantity += item.quantity;
    } else {
      // otherwise, add it to the cart
      this.items.push(item);
    }
  },
  removeItem: function(itemId) {
    // find the index of the item
    const index = this.items.findIndex(i => i.id === itemId);
    if (index !== -1) {
      // if item exists, remove it from the cart
      this.items.splice(index, 1);
    }
  },
  updateQuantity: function(itemId, quantity) {
    // find the index of the item
    const index = this.items.findIndex(i => i.id === itemId);
    if (index !== -1) {
      // if item exists, update the quantity
      this.items[index].quantity = quantity;
    }
  },
  getTotal: function() {
    // get the total price of all items in the cart
    return this.items.reduce((total, item) => total + (item.price * item.quantity), 0);
  }
};

// add event listeners to the "add to cart" buttons
const addToCartButtons = document.querySelectorAll('.add-to-cart');
addToCartButtons.forEach(button => {
  button.addEventListener('click', () => {
    const productId = button.dataset.productId;
    const productName = button.dataset.productName;
    const productPrice = button.dataset.productPrice;
    const productQuantity = parseInt(document.querySelector('input[type="number"]').value);

    const productData = {
      id: productId,
      name: productName,
      price: productPrice,
      quantity: productQuantity
    };

    // add the product to the cart
    cart.addItem(productData);
    console.log(cart.items);
  });
});

// add event listeners to the quantity input fields
const quantityInputs = document.querySelectorAll('input[type="number"]');
quantityInputs.forEach(input => {
  input.addEventListener('change', () => {
    const productId = input.dataset.productId;
    const quantity = parseInt(input.value);

    // update the quantity of the product in the cart
    cart.updateQuantity(productId, quantity);
    console.log(cart.items);
  });
});

// add event listeners to the "remove" buttons in the cart
const removeButtons = document.querySelectorAll('.remove');
removeButtons.forEach(button => {
  button.addEventListener('click', () => {
    const itemId = button.dataset.itemId;

    // remove the item from the cart
    cart.removeItem(itemId);
    console.log(cart.items);
  });
});

// update the total price in the cart
const totalSpan = document.querySelector('.total span');
totalSpan.innerText = cart.getTotal();
In this code, we first define a cart object that has an array of items and several methods for adding, removing, and updating items, as well as getting the total price. We then add event listeners to the "add to cart" buttons that capture the product details and add them to the cart. We also add event listeners to the quantity input fields that update the quantity of the corresponding product in the cart. Finally, we add event listeners to the "remove" buttons in the cart that remove the corresponding item from the cart. We also update the total price in the cart whenever an item is added, removed, or the quantity changes.
;