Sometimes, we want to prevent users from submitting a form by hitting Enter with JavaScript.
In this article, we’ll look at how to prevent users from submitting a form by hitting Enter with JavaScript.
How to prevent users from submitting a form by hitting Enter with JavaScript?
To prevent users from submitting a form by hitting Enter with JavaScript, we can check the keyCode
and keyIdentifier
properties.
For instance, we write
window.addEventListener(
"keydown",
(e) => {
if (
e.keyIdentifier === "U+000A" ||
e.keyIdentifier === "Enter" ||
e.keyCode === 13
) {
e.preventDefault();
return false;
}
},
true
);
to listen to the keydown event on the page with addEventListener
.
In the keydown listener function, we check for the enter key press with
e.keyIdentifier === "U+000A" || e.keyIdentifier === "Enter" || e.keyCode === 13
If any of them is true
, then we call preventDefault
to stop the submission.
Conclusion
To prevent users from submitting a form by hitting Enter with JavaScript, we can check the keyCode
and keyIdentifier
properties.