The other day I was building a form, and I was surprised how event firing works when you press ENTER
on the keyboard.
When you’re on a form field in most browsers, pressing ENTER
on the keyboard triggers the browser to submit the form. This is called implicit submission (thanks Tim). I suspected pressing ENTER
would cause a submit
event to be fired on the form, but it is more nuanced than that.
‘ENTER’ submits the form, even if it contains no submit button. If the form does contain one or more submit buttons:
- pressing
ENTER
results in aclick
event on the submit button of the form - when the submit button is clicked, it submits the form, which triggers a
submit
event on the form
In the above, “the submit button” is the first submit button that exists in your form, the HTML spec calls this the form’s default button.
What surprised me, is that functions that listen to the click
event on your default button, run before the form’s submit
event is fired. Running event.preventDefault()
on the form’s submit event will not stop that click handler from running (thanks Matijs for helping me figure this out).
Comments, likes & shares
No webmentions about this post yet! (Or I've broken my implementation)