Ask any question about JavaScript here... and get an instant response.
Post this Question & Answer:
How can I prevent a form submission when the Enter key is pressed?
Asked on Feb 28, 2026
Answer
To prevent a form submission when the Enter key is pressed, you can add an event listener to the form and check for the Enter key in the "keydown" event. If the Enter key is detected, you can call "preventDefault()" to stop the form from submitting.
<!-- BEGIN COPY / PASTE -->
document.querySelector("form").addEventListener("keydown", function(event) {
if (event.key === "Enter") {
event.preventDefault();
}
});
<!-- END COPY / PASTE -->Additional Comment:
✅ Answered with JavaScript best practices.- This code snippet adds an event listener to the form element.
- It listens for the "keydown" event and checks if the "Enter" key was pressed.
- If the "Enter" key is pressed, "event.preventDefault()" is called to prevent the default form submission behavior.
Recommended Links:
