Home >Web Front-end >JS Tutorial >How to disable pressing the Enter key to submit a form_javascript skills
When automatic submission occurs, there are two possibilities:
The first is to write javascript code. When the user clicks the Enter key, the submission of the form is triggered through the js event listening mechanism.
The second is to take advantage of the default behavior of the browser (at least this is what I found). Browsers have many default behaviors when parsing web pages. For example, if there is a form and a submit button on a page, then when the page is opened, the focus will automatically fall on the submit button. Similarly, if there is only one single-line text input field (text) in a form, the browser will automatically submit the form when the Enter key is pressed in this input field.
We generally know about the first situation and it is easy to understand, but for the default behavior of the second browser, fewer people may know this. Let me take a look at the browser in detail (at least for IE ) the default behavior on form submission.
If the form contains a single-line text input field, no matter how many other types of form components it contains, the form will be automatically submitted when Enter is clicked in the input field.
For example the following code:
<form action="" method="post"> <input type="text" name="sdfsdf"/> <input type="checkbox">sdfsdf <input type="hidden"name="aa"/></form>
If the form contains two or more single-line text input fields, regardless of whether it contains other types of form components, it will not be automatically submitted when pressing the Enter key, for example:
<form action="" method="post" <input type="text" name="sdfsdf"/ <input type="text" name="sddf"/</form
The method is very simple. We already have it in the example we gave above. Just add another text input box. You may say that in order not to automatically submit, you need to add a useless input box, and it contains Will two input boxes be acceptable to end users? In fact, it can be solved. You can hide the newly added input box through style, for example:
<form action="" method="post" <input type="text" name="notautosubmit" style="display:none"/ <input type="text" name="username"/</form
There is also a method to bind the button button enter trigger event:
document.onkeypress = function(){
if(event.keyCode == 13) {search();returnfalse;}} where the search method is the onclick event: