Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why a button is clicked when a form is submitted?

Say, I have a form with a text input and a submit button.

If there are no buttons in the form, just submit event triggers, but if there is at least one button with no type attribute or with type="submit", it clicks it too.

Now, when I enter something in the input and then press Enter, I see that both button click and form submit events are triggered.

Example:

<form>
  <input type="text" />
  <button onclick="alert('submitted');">Submit</button>
</form>

I suppose the form clicks the button automatically on the form submit event.

I wonder the origins and the reason for such behavior? Why do I need the button to be clicked when I submit the form?

like image 423
Sergei Basharov Avatar asked Jun 13 '16 14:06

Sergei Basharov


1 Answers

From the spec:

4.10.22.2 Implicit submission

If the user agent supports letting the user submit a form implicitly (for example, on some platforms hitting the "enter" key while a text field is focused implicitly submits the form), then doing so for a form whose default button has a defined activation behaviour must cause the user agent to run synthetic click activation steps on that default button.

6.3 [synthetic click] Activation

Certain elements in HTML have an activation behaviour, which means that the user can activate them. This triggers a sequence of events dependent on the activation mechanism, and normally culminating in a click event, as described below.

The user agent should allow the user to manually trigger elements that have an activation behaviour, for instance using keyboard or voice input, or through mouse clicks. When the user triggers an element with a defined activation behaviour in a manner other than clicking it, the default action of the interaction event must be to run synthetic click activation steps on the element.

See full script here


So pressing Enter is processed as saying submit in your microphone (with a voice input device). Your browser should behave as if the user has clicked the button to process the click event attached functions properly and improve accessibility for those who can't use a mouse.

like image 144
Florian Lemaitre Avatar answered Sep 23 '22 20:09

Florian Lemaitre