Use onkeydown to automatically submit a form by pressing enter
1. When there is only one <input type = "text" name = "name"/> in the form, pressing the Enter key will automatically submit the form.
- <Form id = "form1" action = "post. php" method = "post">
- <Input type = "text" name = "name"/>
- </Form>
Add another
- <Input type = "text"/>
Press enter and you will not submit it automatically. However, it is quite awkward to display an input box on the cloud page. Then, I found two solutions from the Internet:
(1) Add
- <Input style = "display: none;" type = "text"/>
If the input box is not displayed, it will not be submitted after you press Enter:
- <Form id = "form1" action = "post. php" method = "post">
- <Input type = "text" name = "name"/>
- <Input style = "display: none"/>
- </Form>
(2) Add an onkeydown event and press Enter. The event will not be displayed:
- <Form id = "form1" action = "post. php" method = "post">
- <Input type = "text" name = "name"
- Onkeydown = "if (event. keyCode = 13) return false;"/>
- </Form>
If you want to add a carriage return event, you can add a judgment submission form in the onkeydown event:
- <Form id = "form1" action = "post. php" method = "post">
- <Input style = "display: none"/>
- <Input type = "text" name = "name" onkeydown = "if (event. keyCode = 13) {gosubmit () ;}"/>
- </Form>
Sometimes we want to press enter in the input element to submit a form, but sometimes we do not want. For example, you want to directly press the Enter key to submit the form immediately after entering the keywords. In some complex forms, you may need to avoid incorrect input keys that trigger the form submission when the form is not completed.
To control these behaviors, you do not need to use JS. the browser has already done these operations for us. Here we will summarize several rules:
If there is a type = "submit" button in the form, the Enter key takes effect.
If there is only one input of type = "text" in the form, no matter what type the button is, the Enter key takes effect.
If the button does not use input, but a button, and no type is added, the default value is type = button in IE, and the default value is type = submit in FX.
Other form elements such as textarea and select do not affect the trigger rules. radio checkbox does not affect the trigger rules. However, in FX, the Return key is returned and the response is not returned in 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 better to add a background image with CSS.