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 Feb 27, 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 Enter key is pressed. If it is, you can call `event.preventDefault()` to stop the form submission.
<!-- BEGIN COPY / PASTE -->
<form>
<input type="text" id="myInput" placeholder="Type something...">
<input type="submit" value="Submit">
</form>
<script>
document.getElementById("myInput").addEventListener("keydown", function(event) {
if (event.key === "Enter") {
event.preventDefault();
}
});
</script>
<!-- END COPY / PASTE -->Additional Comment:
✅ Answered with JavaScript best practices.- The event listener is attached to the text field with the ID "myInput".
- The "keydown" event is used to detect when any key is pressed.
- The condition `event.key === "Enter"` checks if the pressed key is the Enter key.
- `event.preventDefault()` stops the default action, which is form submission in this context.
Recommended Links:
