I have a form that has a submit button in it somewhere.
However, I would like to somehow \'catch\' the submit event and prevent it from occurring.
Is there s
Attach an event listener to the form using .addEventListener() and then call the .preventDefault() method on event:
const element = document.querySelector('form');
element.addEventListener('submit', event => {
event.preventDefault();
// actual logic, e.g. validate the form
console.log('Form submission cancelled.');
});
I think it's a better solution than defining a submit event handler inline with the onsubmit attribute because it separates webpage logic and structure. It's much easier to maintain a project where logic is separated from HTML. See: Unobtrusive JavaScript.
Using the .onsubmit property of the form DOM object is not a good idea because it prevents you from attaching multiple submit callbacks to one element. See addEventListener vs onclick
.