document.addEventListener("DOMContentLoaded", function () {
const quantityInputs = document.querySelectorAll('input[type="number"]');
quantityInputs.forEach(function (input) {
input.setAttribute("min", "6");
input.setAttribute("step", "6");
// Attach event listeners for manual input validation
input.addEventListener("change", function () {
validateQuantity(this);
// Get the line item key for this input (from a data attribute or similar)
const lineItemKey = input.closest("[data-line-item-key]").dataset.lineItemKey;
// Send the updated quantity to Shopify via AJAX
updateCart(lineItemKey, parseInt(this.value, 10));
});
});
// Button listeners for quantity increment/decrement
document.querySelectorAll("[data-quantity]").forEach((button) => {
button.addEventListener("click", function (event) {
event.preventDefault();
const input = this.closest(".cart__quantity").querySelector('input[type="number"]');
const direction = this.dataset.quantity;
adjustQuantity(direction, input);
// Get the line item key for this input
const lineItemKey = input.closest("[data-line-item-key]").dataset.lineItemKey;
// Send the updated quantity to Shopify via AJAX
updateCart(lineItemKey, parseInt(input.value, 10));
});
});
// Adjust quantity function
function adjustQuantity(direction, input) {
const step = parseInt(input.step, 10) || 6;
const min = parseInt(input.min, 10) || 6;
let currentValue = parseInt(input.value, 10) || min;
if (direction === "up") {
currentValue += step;
} else if (direction === "down") {
currentValue = Math.max(min, currentValue - step);
}
input.value = currentValue;
input.dispatchEvent(new Event("change", { bubbles: true }));
}
// Validate manual input
function validateQuantity(input) {
const min = parseInt(input.min, 10) || 6;
const step = parseInt(input.step, 10) || 6;
let value = parseInt(input.value, 10);
if (isNaN(value) || value < min || value % step !== 0) {
value = Math.max(min, Math.round(value / step) * step);
input.value = value;
}
}
// Update cart via AJAX
function updateCart(lineItemKey, quantity) {
fetch("/cart/update.js", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
updates: {
[lineItemKey]: quantity,
},
}),
})
.then((response) => response.json())
.then((cart) => {
updateCartTotals(cart);
})
.catch((error) => {
console.error("Error updating cart:", error);
});
}
// Update cart totals dynamically
function updateCartTotals(cart) {
const subtotalElement = document.querySelector("#cart-subtotal");
if (subtotalElement) {
subtotalElement.textContent = Shopify.formatMoney(cart.total_price);
}
cart.items.forEach((item) => {
const lineItemRow = document.querySelector(`[data-line-item-key="${item.key}"]`);
if (lineItemRow) {
const linePriceElement = lineItemRow.querySelector(".cart__price");
if (linePriceElement) {
linePriceElement.textContent = Shopify.formatMoney(item.line_price);
}
}
});
}
});