How to trigger a submit event with Enter?
Every couple of days I pick an HTML element or attribute I want to master. Two days ago I was looking into formaction
and formmethod
attributes. While I was playing around with these attributes, I realized I must first find all the ways to trigger a submit event using Enter. This is a write-up of my findings.
Being able to submit a <form>
with Enter is a standard feature on the web. In most modern web apps, <form>
content is submitted using JavaScript, either by using XMLHttpRequest
or fetch
. In this article, however, I explore a plain HTML approach of doing this.
There are three preconditions that need to be satisfied in order for Enter to submit <form>
. First, the type of <input>
element must treat Enter as a submit-triggering command. Of all the input types, seventeen <input>
types listed below handle Enter this way.
-
<input type="checkbox">
-
<input type="date">
-
<input type="datetime">
obsolete -
<input type="datetime-local">
-
<input type="email">
-
<input type="image">
-
<input type="month">
-
<input type="number">
-
<input type="password">
-
<input type="radio">
-
<input type="search">
-
<input type="submit">
-
<input type="tel">
-
<input type="text">
-
<input type="time">
-
<input type="url">
-
<input type="week">
Second, the <input>
must be accompanied by at least one submit-triggering element listed below, unless that <input>
is type="submit"
or type="image"
.
-
<input type="submit">
-
<input type="image">
-
<button>
, which by default istype="submit"
Third, those elements must be inside a <form>
.
To summarize, to submit a form using Enter in plain HTML you need:
-
an Enter-able
<input>
element -
an additional submit-triggering element, unless
<input>
istype="submit"
ortype="image"
-
a
<form>
that contains the<input>
element(s)
In the next article I explain how formaction
, formmethod
and similar attributes interplay with Enter-triggered <form>
submissions.