<form>
Example
button.addEventListener("click", () => {
send(new FormData(form));
});form.addEventListener("submit", (event) => {
event.preventDefault();
send(new FormData(form));
});The submit event fires for the Enter key, button clicks and requestSubmit(), and only after validation passes.
Common mistakes
- Forgetting
nameon inputs, so the server receives empty data. - Listening to the button's
clickinstead of the form'ssubmit, which breaks Enter to submit.
Key points
- Every control has a
name, so its value is submitted. - Every control has a visible
<label>linked withforandid. - Forms that change data use
method='post', not the default 'get'. - Submission is handled on the form's
submitevent, not on the button'sclick.
Interview questions
What is the default method of a form?
The default is 'get', which puts values in the URL. Use 'post' for sensitive data or changes.
Why does my form reload the page?
Submitting navigates to the action URL by default. Call event.preventDefault() in the submit handler to handle it with JS.