Ask any question about JavaScript here... and get an instant response.
Post this Question & Answer:
How can I prevent a form from submitting when pressing Enter in a text field?
Asked on Apr 06, 2026
Answer
To prevent a form from submitting when pressing Enter in a text field, you can add an event listener to the text field that captures the "keydown" event and checks if the pressed key is Enter. If it is, you can call `preventDefault()` on the event.
<!-- BEGIN COPY / PASTE -->
document.getElementById("myTextField").addEventListener("keydown", function(event) {
if (event.key === "Enter") {
event.preventDefault();
}
});
<!-- END COPY / PASTE -->Additional Comment:
✅ Answered with JavaScript best practices.- This code attaches an event listener to a text field with the ID "myTextField".
- The "keydown" event is used to detect when a key is pressed.
- If the Enter key is pressed, `event.preventDefault()` stops the form from being submitted.
- Ensure the text field has the correct ID in your HTML.
Recommended Links:
