Let’s see more details of them.
There are two main ways to submit a form:
- The first – to click
- The second – press Enter on an input field.
Both actions lead to
submit event on the form. The handler can check the data, and if there are errors, show them and call
event.preventDefault(), then the form won’t be sent to the server.
In the form below:
- Go into the text field and press Enter.
Both actions show
alert and the form is not sent anywhere due to
<form onsubmit="alert('submit!');return false"> First: Enter in the input field <input type="text" value="text"><br> Second: Click "submit": <input type="submit" value="Submit"> </form>
When a form is sent using Enter on an input field, a
click event triggers on the
That’s rather funny, because there was no click at all.
Here’s the demo:
<form onsubmit="return false"> <input type="text" size="30" value="Focus here and press enter"> <input type="submit" value="Submit" onclick="alert('click')"> </form>
To submit a form to the server manually, we can call
submit event is not generated. It is assumed that if the programmer calls
form.submit(), then the script already did all related processing.
Sometimes that’s used to manually create and send a form, like this:
let form = document.createElement('form'); form.action = 'https://google.com/search'; form.method = 'GET'; form.innerHTML = '<input name="q" value="test">'; // the form must be in the document to submit it document.body.append(form); form.submit();