Web page form press enter to solve the problem of auto submission

  • 2020-03-30 04:15:00
  • OfStack

1. When there is only one < Input type = "text" name = "name" / > Press enter to automatically submit the form.


<form id="form1" action="post.php" method="post">  
    <input type="text" name="name" />  
</form> 

Add one more


<input type="text" /> 

Pressing enter will not automatically submit, but it is awkward to display an unintelligible input box on the page. After that, I found two solutions from the Internet:
(1) add one


<input style="display: none;" type="text" /> 

Do not display the input box, and then after the return will not submit:


<form id="form1" action="post.php" method="post">  
    <input type="text" name="name" />  
    <input style="display:none" />  
</form> 

(2) add an onkeydown event, and it will not be displayed after entering:


<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>

To control these behaviors, we do not need to use JS, the browser has done these processing for us, here is a summary of a few rules:

If there is a type="submit" button in the form, the enter key takes effect.

If there is only one type="text" input in the form, the enter key takes effect regardless of the type of button.

If the button is not input but is a button without type, IE defaults to type=button and FX defaults to type=submit.

Other form elements such as textarea and select do not affect, and radio checkbox does not affect the trigger rule, but it responds to the enter key under FX and not under IE.

Type ="image" input, the effect is the same as type="submit", I do not know why such a type is designed, it is not recommended to use, should be added with CSS background more appropriate.


Related articles: