Form not submitting when pressing enter

后端 未结 6 1060
长发绾君心
长发绾君心 2020-12-15 03:11

I have the following HTML/JS/jQuery Code. This code represents a login form that is presented modally to the user to allow them to login. The problem is, when I hit enter, t

6条回答
  •  自闭症患者
    2020-12-15 03:57

    I was struggling with this same issue; one of my forms was submitting when pressing "enter" in the text fields with no problem; another, similar, form on the same page wouldn't submit at all, for the life of me.

    Neither field had a submit button, and neither was using javascript to do any submission.

    What I found, is that when there is only a single text field in a form, pressing 'enter' in the text field will automatically submit; but if there is more than one (regular (i.e. single-line) text input) field, it does nothing, unless there is also some kind of 'submit' button.

    Apparently this is part of the HTML 2.0 specification:

    When there is only one single-line text input field in a form, the user agent should accept Enter in that field as a request to submit the form.

    An old, but apparently still valid, and interesting, further discussion here.

    ... evidently meant as a convenient way to submit simple queries, but reducing the risk, on a complex form, of prematurely submitting it while trying to fill it in. Numerous browser implementers (e.g Netscape, Opera, various versions of Lynx,...) followed this advice, though it seems with slightly different interpretations.

    I made a JSFiddle to demonstrate. As far as I can tell (lazily just testing with Chrome), the form will submit on "Enter" if there's only one text field, or if there's a submit button, even if it's hidden.

    (EDIT: I later found that it also does seem work if there are other input fields which are not a regular, single-line text input ... e.g., textareas, selects, etc. -- thanks to @user3292788 for that information. Updated the JSFiddle to reflect this).

    Form with one text field only, no submit button

    Seems to submit automatically when pressing 'enter' in the first text field

    Form with two text fields, no submit button

    Won't submit when pressing 'enter' in the forms ...

    Form with two text fields and a submit button ...

    Now it submits with 'enter' key

    Form with two text fields and a HIDDEN submit button ...

    Seems to work, even with submit hidden ...

    Form with no action or method attribute, HIDDEN submit button ...

    Even this seems to work.

    Form with multiple fields, but only one text input, no submit button.

    This seems to work as well.

提交回复
热议问题