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
The following works as of now (tested in chrome and firefox):
<form onsubmit="event.preventDefault(); return validateMyForm();">
where validateMyForm() is a function that returns false
if validation fails. The key point is to use the name event
. We cannot use for e.g. e.preventDefault()
Here my answer :
<form onsubmit="event.preventDefault();searchOrder(event);">
...
</form>
<script>
const searchOrder = e => {
e.preventDefault();
const name = e.target.name.value;
renderSearching();
return false;
}
</script>
I add event.preventDefault();
on onsubmit
and it works.
For prevent form from submittion you only need to do this.
<form onsubmit="event.preventDefault()">
.....
</form>
By using above code this will prevent your form submittion.
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.');
});
<form>
<button type="submit">Submit</button>
</form>
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
.