When we have more than 1 submit button in a HTML form, we may want to disable the “Enter” button from triggering the default submit button. Below shows 2 ways to do it:
1. Using JavaScript
Detect “Enter” key on “Text” & “Password” input. This approach works on all major browsers (including I.E. 11)
Add below jQuery event handler in every page (put it in a global js file)
$("form.noEnterKeySubmit").find("input[type='text'], input[type='password']")
.on('keyup keypress', function (e) {
if (e.keyCode == 13) {
e.preventDefault();
return false;
}
});
Then mark the form with class noEnterKeySubmit
<form action="myAction" class="noEnterKeySubmit" method="post">
...
2. Using “disabled” submit button
As per HTML5 spec, the default button is the first submit button in a form. So we can effectively prevent “Enter” key form submitting by putting a disabled & hidden submit button as the first button in the form.
The advantage is no JavaScript needed, but the downside is this does not work on I.E. & Safari
<form action="...">
<!-- Prevent implicit submission of the form -->
<button type="submit" disabled style="display: none" aria-hidden="true"></button>
<!-- ... -->
<button type="submit">Submit</button>
</form>