Two primary ways of submitting a form exist:
- Clicking either <input type="submit"> or <input type="image">.
- Pressing Enter on an input field.
Both of the actions above leads to submit an event on the form. The handler is capable of checking the data. In case there are errors, it will show them and call event.preventDefault(). Then, the form will not be sent to the server. In the example below, both of the actions show an alert, and due to the return false, the form isn’t sent anywhere:
<html> <head> <title>Title of the Document</title> </head> <body> <form onsubmit="alert('Submit!');return false"> Enter in the input field: <input type="text" value="text"> <br> Click "Submit": <input type="submit" value="Submit"> </form> </body> </html>
So, in this case, it is necessary to go into the text field and press Enter, then click <input type="submit">.
Relation between Submit and Click¶
At the time a form is sent inserting Enter on an input field, a click event occurs on the <input type="submit">.
This situation can look a little funny, as no click was performed at all.
It is illustrated in the demo below:
<html> <head> <title>Title of the Document</title> </head> <body> <form onsubmit="return false"> <input type="text" size="40" value="Write here and press enter"> <input type="submit" value="Submit" onclick="alert('Clicked!')"> </form> </body> </html>
You can call form.submit() for submitting a form manually. But, then the submit event may not be created. It is supposed that if the developer calls form.submit() then the script has already done all the processing related to it.
So, sometimes it is necessary to manually create and send a form, as follows:
let form = document.createElement('form'); form.action = 'https://www.w3docs.com/'; form.method = 'GET'; form.innerHTML = '<input name="q" value="test">'; // the form must be in the document for submitting it document.body.append(form); form.submit();
To summarize the chapter, let’s note that the event and method submit relate to the most important parts of a programmer’s daily routine.
It can be efficiently used to create and send own forms to the server.