Here’s what I wrote to prevent add to cart form submission on product detail page, I intended to show a custom message or alert if some fields are empty, the strange thing is no matter what I tried, it still submits the form when clicking add to cart button, i don’t know what is wrong:
document.addEventListener('DOMContentLoaded', function () {
const productForm = document.querySelector('form[action^="/cart/add"]');
if (productForm) {
productForm.addEventListener('submit', function (event) {
event.preventDefault(); // Prevent form submission
alert('Add to Cart submission prevented.');
});
}
});
can anyone help me? thanks
@kirbe_Admin ,
Your code is correct in principle, but it’s likely being overridden by other event listeners—possibly from the theme’s default JavaScript.
To provide a more accurate solution, please share your store URL or details about the theme you’re using. This will help me inspect the form behavior directly and suggest a fix that works with your store’s setup.
.
here’s my store, luxdrape.com, thanks a lot, you can try on any product detail page. the theme is dawn
@kirbe_Admin ,
Search the product-form.js in your theme. There is onSubmitHandler function put your alert there and review in front side.
thanks a lot, you saved my day, i will try and post the result here
it didn’t popup any alert, my code is like the following:
onSubmitHandler(evt) {
evt.preventDefault();
alert("hello world");
return
`````
i don’t know if it works on your end.
Are you using any app for product page ?
Above code is worked with dawn theme :
Test store URL → my-test-dawn-store
Password : agheol
If there is any app then need to check with your store and withour access its not possible find solution.
I’m not sure, i am using a product options plugin, maybe because of that, i will check to make sure
Hi @kirbe_Admin
It depends on the theme you use, so I’d suggest you look into how it handles the cart submission first.
Most themes already use a custom implementation with the storefront API. The e.preventDefault()
only prevents HTML <form>
submissions, thus not preventing submissions though the API.
Edit: mobile browsing trolled me, so I didn’t notice it was already answered 