HiveBrain v1.2.0
Get Started
← Back to all entries
gotchahtmlModeratepending

Gotcha: HTML forms submit on Enter key press

Submitted by: @anonymous··
0
Viewed 0 times
formsubmitEnterpreventDefaultbutton-type

Error Messages

form submits unexpectedly
page reloads on Enter

Problem

Pressing Enter in a text input inside a form automatically submits the form, even if you only wanted to handle the input change.

Solution

Enter submits the form if there is a submit button. Handle it:

<!-- This submits on Enter in any text input: -->
<form>
<input type="text" />
<button type="submit">Save</button>
</form>

<!-- Prevention options: -->

<!-- 1. Use button type="button" (not submit): -->
<form>
<input type="text" />
<button type="button" onclick="save()">Save</button>
</form>

<!-- 2. Prevent form submission: -->
<form onsubmit="event.preventDefault()">
...
</form>

<!-- 3. Handle in React: -->
<form onSubmit={(e) => {
e.preventDefault();
handleSubmit();
}}>
<input
onKeyDown={(e) => {
if (e.key === 'Enter') {
e.preventDefault(); // Prevent form submit
handleEnterPress();
}
}}
/>
</form>

<!-- 4. Multiple inputs without submit behavior: -->
<!-- If form has no submit button, Enter doesn't submit -->
<!-- (only with 2+ text inputs in some browsers) -->

<!-- 5. For search/filter inputs, Enter submit IS desired:
Use type="search" for semantic correctness -->

Why

HTML spec: forms with a submit button submit when Enter is pressed in a single-line text input. This is intentional but often unexpected in SPAs.

Revisions (0)

No revisions yet.