But there is third way to submit form. That’s the implicit submission of form when pressing the enter key under some situations. The form implicit subbmission supported by all browsers, and html spec strongly recommand do this.
Implicit submission situation 1
The form will be submitted automatically when there is only one input element in the form and pressing the enter key in the input element.
1 2 3 4
The form will be submitted and get the data from abc.txt file when we press the enter key in the input element.
But if the form has multiple input elements, the form can not be submitted automatically. like below codes.
1 2 3 4 5 6
Implicit submission situation 2
For multiple input elements in the form situation, the form can not be submitted automatically. So how to make it implicit submission. This is second situation we are introducing.
If the form has submit type element(input, button), the form will be submitted when pressing the enter key in the input element regardless of how many input elements in this form.
1 2 3 4 5 6 7
submit event handler on the form, not a
click handler on a button.
How to suppress it
The solution is very simple, just prevent the event trigger when pressing the enter key. So we can deal with it in the
keypress event handler.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
Note, the code of enter key is 13. Using
event.preventDefault() to stop the form submission when the keycode is 13. And for above codes, we only suppress the age input element, so when pressing enter key in the name input element, the form still is submitted.