HTML forms with multiple buttons
Lets say you have an HTML form with multiple buttons. One button submits the form, but the others do something else. Here’s a simple example:
<form>
<label>
Email address
<input type="email" name="email" />
</label>
<button onClick="handleCancel()">Cancel</button>
<button>Save</button>
</form>
I might type my email address into the form, press Enter, and… oops. For some reason, pressing Enter chooses the Cancel button.
The fix is to add type="button"
to any button which should not submit the form, and type="submit"
to any buttons which should submit the form, like so:
<form>
<label>
Email address
<input type="email" name="email" />
</label>
<button type="button" onClick="handleCancel()">Cancel</button>
<button type="submit">Save</button>
</form>
Pressing Enter will now submit the form, as expected.