Implicit form submission doesn't work always
Written by Stefan Judis
- Published at
- Updated at
- Reading time
- 1min
This post is part of my Today I learned series in which I share all my web development learnings.
If a form submits by pressing ENTER
on a focused input field this is an implicit form submission.
But does every HTML form submit on ENTER
?
HTML forms implicitly submit under two conditions:
- the form has a submit button.
- the form has only one input element.
So let me share a quick example:
<form onsubmit="alert(1)">
<!-- this will alert if you press `ENTER` while "foo" is focused -->
<input name="foo" />
</form>
<form onsubmit="alert(2)">
<!-- this won't -->
<input name="foo" />
<input name="bar" />
</form>
Tip: if you want to work around this behavior, you can always add a hidden submit button. And if you want to read the spec defining form submissions, here we go.
If you enjoyed this article...
Join 5.3k readers and learn something new every week with Web Weekly.