You can stop it from submitting by listening to the submit
event and calling the preventDefault()
method:
// Select the form
var form = document.querySelector("form");
// Stop it from submitting
form.addEventListener("submit", function (event) {
event.preventDefault();
});
There are other things you can do, such as:
input
fieldI won't get into them, though.
I would generally advise against disabling an element's default behaviour unless you really need to.
Form validation is the only real use case for me.
The thing to understand is that the preventDefault()
method disables the default behaviour of an element.
You can only call the preventDefault()
method if an event is cancelable.
There are two ways to find out:
cancelable
propertyLet's say I want to find out if the submit
event is cancelable. I would go to my search engine and look for "mdn submit event". This takes me to the page for the submit
event. At the top of the page, I can see that the event is indeed cancelable.
cancelable
propertyThe other way is to check the event's cancelable
property. It will be true
or false
depending on the event in question:
var form = document.querySelector("form");
form.addEventListener("submit", function (event) {
// This WILL run because the submit event IS cancelable
if (event.cancelable) {
event.preventDefault();
}
});