The preventDefault()
method of the Event
interface lets you prevent the default action of an event.
Preventing form submission
I'd say this is the most frequent use case for me. If a form has validation errors, you'll want to stop it from submitting.
Given an HTML form:
<form>
<p>
<label for="name">Name</label>
<input id="name" type="text" name="name">
</p>
<p>
<label for="email">Email</label>
<input id="email" type="email" name="email">
</p>
<p>
<label for="message">Message</label>
<textarea id="message" name="message"></textarea>
</p>
<p>
<button type="submit">Submit</button>
</p>
</form>
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();
});
Other examples
There are other things you can do, such as:
- Suppressing a link
- Disabling a checkbox
- Preventing typing inside an
input
field
I 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.
The event must be cancelable
You can only call the preventDefault()
method if an event is cancelable.
There are two ways to find out:
- Check the MDN Web Docs
- Check the event's
cancelable
property
The MDN Web Docs
Let'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.
The cancelable
property
The 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();
}
});