<form>

Term side of the Card.
Topic: Forms
Unit title: <form>
Categories: Tag
Explanation side of the Card

Explanation: The element that is used to collect user input through various controls like text fields, checkboxes and buttons. The data entered in a form can be sent to a server for processing, making it a key element in user interaction on the web.

Browser compatibility:
  • The chrome browser supports this feature starting from version 1.
  • The edge browser supports this feature starting from version 12.
  • The firefox browser supports this feature starting from version 1.
  • The safari browser supports this feature starting from version 4.
Availability: 

Example

Wrongjs
button.addEventListener("click", () => {
  send(new FormData(form));
});
Rightjs
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 name on inputs, so the server receives empty data.
  • Listening to the button's click instead of the form's submit, which breaks Enter to submit.

Key points

  • Every control has a name, so its value is submitted.
  • Every control has a visible <label> linked with for and id.
  • Forms that change data use method='post', not the default 'get'.
  • Submission is handled on the form's submit event, not on the button's click.

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.

Analytics cookiesWe'd like to use analytics cookies to see which pages are useful. They're set only if you accept. Privacy Policy