How to limit cart quantity per order

Hi all,

I encountered a problem limiting each order to only 10 items in cart. I attempted to solve this issue by adjusting custom attributes and embedding custom code from Slater(from below), but none of these solutions worked. (I am a newb in javascript)

<script>
document.addEventListener('DOMContentLoaded', function() {
const addToCartButtons = document.querySelectorAll('.OrderButton');
let totalCartQuantity = 0;

addToCartButtons.forEach(button => {
    button.addEventListener('click', function() {
        const menuItem = button.closest('.MenuItem');
        const quantityInput = menuItem.querySelector('.quantity-input');
        const quantity = parseInt(quantityInput.value);

        totalCartQuantity += quantity;

        if (totalCartQuantity > 10) {
            const errorMessage = document.createElement('div');
            errorMessage.textContent = 'You can only add up to 5 items to the cart.';
            errorMessage.classList.add('error-message_1');
            menuItem.appendChild(errorMessage);

            console.log('Total cart quantity exceeds 10');
            console.log('Error message displayed');

            setTimeout(() => {
                errorMessage.remove();
                console.log('Error message removed after 3 seconds');
            }, 3000); // Remove the error message after 3 seconds
        }
    });
});

});
</script>

If anyone has encountered the same problem and found a successful solution, I would be happy to hear it.

Thanks in advance!!!

Hi Sandy, what is the link to this published page?
Any product page will be fine as long as it has this mechanism, and your webflow.io domain is fine as well.