Removing cart item when quantity is selected to 0 .

Removing cart item when quantity is selected to 0 .

jagjeet
Shopify Partner
5 0 0

Hi

  I have written code when user reduces the cart item quantity to 0 then it is removed from cart. In chrome this is working fine . But in Firefox , when user is reducing the item to 0 then its removing the current item but making the next item value 0 in front end . 

 

Below is the code.

 

 

 

 

 

 

$(document).ready(function() { 

  var plusButtons = document.querySelectorAll('.plus');
  var minusButtons = document.querySelectorAll('.minus');
  
  plusButtons.forEach(function(button) {
    button.addEventListener('click', function(event) {
      event.preventDefault();
      
      var quantityDiv = button.closest('.quantity');
      var input = quantityDiv.querySelector('.quantity-input');
      var currentQuantity = parseInt(input.value);
      var inventoryQuantity = parseInt(quantityDiv.getAttribute('data-inventory-quantity'));
      
      if (currentQuantity + 1 > inventoryQuantity) {
        alert('You cannot add more than the available stock.');
      } else {
        updateCartQuantity(button.getAttribute('data-line'), currentQuantity + 1, input);
      }
    });
  });

  minusButtons.forEach(function(button) {
    button.addEventListener('click', function(event) {
  
      event.preventDefault();
      event.stopPropagation();
      var quantityDiv = button.closest('.quantity');
      var input = quantityDiv.querySelector('.quantity-input');
      var currentQuantity = parseInt(input.value);
      
      if (currentQuantity > 0) {
        updateCartQuantity(button.getAttribute('data-line'), currentQuantity - 1, input);
      }  
    });
  });

  function updateCartQuantity(line, quantity, input) {
    fetch(`/cart/change.js`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json'
      },
      body: JSON.stringify({
        line: line,
        quantity: quantity
      })
    })
    .then(response => response.json())
    .then(data => {
      console.log('Cart updated', data);
      input.value = quantity;
      // Refresh the page after updating
      window.location.reload();
    })
    .catch(error => {
      console.error('Error updating cart:', error);
    });
  }
});

 

 

 

 

 

 

Replies 0 (0)