Attach an event listener to the form using .addEventListener()
and then call the .preventDefault()
method on event
:
const element = document.querySelector('form');_x000D_
element.addEventListener('submit', event => {_x000D_
event.preventDefault();_x000D_
// actual logic, e.g. validate the form_x000D_
console.log('Form submission cancelled.');_x000D_
});
_x000D_
<form>_x000D_
<button type="submit">Submit</button>_x000D_
</form>
_x000D_
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
.