How to Implement Quantity-Based Fee Addition

Topic summary

A user is seeking help with a JavaScript code snippet designed to add quantity-based fees to a Shopify cart. The code attempts to:

Intended Functionality:

  • Add a setup fee product when quantity is 1-5
  • Add a membership fee product when quantity is 6-50
  • Prevent default form submission and redirect to cart after adding products

Implementation Details:

  • Uses Shopify’s /cart/add.js API endpoint
  • Listens for ‘Add to Cart’ button clicks via event listener
  • Reads quantity from input field to determine which fee to apply

Current Status:

  • The code is not working as expected
  • No responses or solutions have been provided yet
  • The discussion remains open with the original poster awaiting assistance
Summarized with AI on October 30. AI used: claude-sonnet-4-5-20250929.

here is my code below and it’s not working, can anyone help?

document.addEventListener(“DOMContentLoaded”, function() {
// IDs of the hidden fee products
const setupFeeProductId = ‘9691437105432;
const membershipFeeProductId = ‘9691438252312’;
// Function to add a product to the cart
function addToCart(productId, quantity) {
fetch(’/cart/add.js’, {
method: ‘POST’,
headers: { ‘Content-Type’: ‘application/json’ },
body: JSON.stringify({
items: [{ id: productId, quantity: quantity }]
})
}).then(response => response.json())
.then(data => {
console.log(‘Product added to cart:’, data);
window.location.href = ‘/cart’; // Redirect to cart page
}).catch(error => {
console.error(‘Error adding product to cart:’, error);
});
}
// Listen for the ‘Add to Cart’ button click
const addToCartButton = document.querySelector(‘form[action=“/cart/add”] button[type=“submit”]’);
if (addToCartButton) {
addToCartButton.addEventListener(‘click’, function(event) {
event.preventDefault(); // Prevent default form submission
// Get the selected quantity
const quantityInput = document.querySelector(‘input[name=“quantity”]’);
const quantity = parseInt(quantityInput.value, 10);
// Determine which fee to add based on quantity
if (quantity >= 1 && quantity <= 5) {
// Add the main product and setup fee product to the cart
addToCart(‘{{ product.variants.first.id }}’, quantity);
addToCart(setupFeeProductId, 1);
} else if (quantity >= 6 && quantity <= 50) {
// Add the main product and membership fee products to the cart
addToCart(‘{{ product.variants.first.id }}’, quantity);
addToCart(membershipFeeProductId, quantity);
} else {
alert(‘Please select a quantity between 1 and
50.’);
}
});
}
});