Why a button is clicked when a form is submitted?

前端 未结 2 1579
礼貌的吻别
礼貌的吻别 2021-02-20 12:27

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 ty

相关标签:
2条回答
  • 2021-02-20 12:56

    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.

    0 讨论(0)
  • 2021-02-20 13:02

    It actually doesn't automatically press the button, that isn't what's submitting the form. The form is being submitted because that's a default characteristic of text boxes - if you have focus in the text box, pressing the enter key will cause an attempt to submit the form. This article goes into a deeper explanation: https://www.tjvantoll.com/2013/01/01/enter-should-submit-forms-stop-messing-with-that/

    EDIT: Actually, more specifically, a form will only submit on the enter key if: 1)A submit button exists in the form, or 2)The form only contains one text input

    If neither of these conditions is true, then the enter key should not submit the form

    0 讨论(0)
提交回复
热议问题