Sometimes we want to hit the Enter key in the text box (input element) to submit the form (form), but sometimes we don't want this. For example, for search behavior, you want to directly press the Enter key after entering the keywords to submit the form immediately. For some complex forms, you may want to avoid accidentally pressing the Enter key to trigger the form submission before completing the form filling.
To control these behaviors, there is no need to resort to JS. The browser has already done this for us. Here are a few rules:
If there is a button with type="submit" in the form , the Enter key takes effect.
If there is only one input with type="text" in the form, regardless of the button type, the Enter key will take effect.
If the button is not input, but button, and no type is added, the default is type=button in IE and type=submit in FX.
Other form elements such as textarea and select are not affected, and the radio checkbox does not affect the triggering rules, but it will respond to the enter key under FX but not under IE.
The input of type="image" has the same effect as type="submit". I don’t know why such a type is designed. It is not recommended. It is more appropriate to use CSS to add a background image.
In actual application, it is easy to make the form respond to the Enter key. Just make sure there is a button with type="submit" in the form. And what should I do when there is only one text box and I don’t want to respond to the Enter key? My method is a bit awkward, which is to write another meaningless text box and hide it. According to rule 3, when we use buttons, try to explicitly declare the type to ensure consistent browser performance.
Made a DEMO listing some examples.
Run the code box