Skip to content
Tutorials Center
My learning

Topics

Lesson 63 of 122 ยท Forms

Forms

Learn how HTML forms collect input, how the browser turns fields into name=value pairs, when to use GET or POST, and how to handle submit in JavaScript.

Every time you search a site, sign in, leave a comment or check out of a shop, you are using a form. Forms are how a web page collects information from a person and hands it to a server. They are one of the oldest features of HTML, and still one of the most important.

In this lesson you will build your first form, see exactly what the browser sends when it is submitted, learn the difference between GET and POST, and catch the submission with JavaScript. The rest of this chapter then looks at each kind of control in detail.

The <form> element

A form is a <form> element wrapped around a set of controls: text boxes, checkboxes, drop-downs and buttons. Here is a tiny one:

HTML
<form action="/subscribe" method="post">
  <label for="email">Email address</label>
  <input type="email" id="email" name="email">

  <button>Subscribe</button>
</form>

Three things work together here:

  • <form> groups the controls and says where the data goes (action) and how it travels (method).
  • <input> is the control the person types into. Its name is the key the server will receive.
  • <button> submits the form. A button inside a form submits it by default.

The <label> gives the field a visible, clickable name that screen readers announce. Every control needs one. You will learn all the ways to write labels in Labels, Fieldsets and Legends.

What happens when you submit

When someone presses the submit button, or presses Enter while typing in a single-line text field, the browser:

  1. Checks the form's built-in validation rules (more on that in Form Validation).
  2. Collects every control that has a name, is not disabled, and (for checkboxes and radio buttons) is checked.
  3. Turns each one into a name=value pair, such as [email protected].
  4. Sends those pairs to the action URL using the method, and shows whatever page the server sends back.

That list of pairs is all the server ever sees. It does not see your labels, your layout or your CSS. If a control has no name, it is simply left out, which is one of the most common beginner bugs.

No name, no data. An id is for labels, CSS and JavaScript. The name is what gets submitted. Most controls need both, and they are often (but not always) the same word.

Seeing the data yourself

The examples on this site never send anything to a real server. Instead, each one listens for the form's submit event, stops the real submission and prints the pairs the browser would have sent. You will see this same short script in every lesson of this chapter:

Your first form

Fill in all three fields and press Send. The nickname never appears in the output, because that input has no name. Try pressing Enter inside a text field too: that submits the form just like the button.

Here is what the script does, line by line:

  • addEventListener("submit", ...) runs a function whenever the form is submitted.
  • event.preventDefault() cancels the real submission, so the page stays put.
  • new FormData(event.target, event.submitter) asks the browser to collect the form's data exactly as it would for a real submission. The second argument adds the button that was clicked, if that button has a name (you will use that trick in Text Areas and Buttons).
  • The loop writes each pair on its own line into the <pre> element.

You do not need to understand every detail of the JavaScript yet. If you want to, Event Attributes and Event Listeners and The Document Object Model cover it properly.

The action attribute

action is the URL that receives the data. It can be absolute (https://example.com/search), root-relative (/search) or relative to the current page (search). If you leave it out, the form submits to the current page's own URL, which is handy when the same page both shows and processes a form.

On a real site, action points at code on your server: a Laravel route, a PHP script, a serverless function, and so on. HTML only describes the form; something on the server must read the pairs and decide what to do with them.

GET or POST?

The method attribute decides how the pairs travel. There are two everyday values.

method="get" (the default)

With GET, the browser adds the pairs to the end of the URL as a query string:

HTML
<form action="/search" method="get">
  <label for="q">Search recipes</label>
  <input type="search" id="q" name="q">
  <button>Search</button>
</form>

Searching for lemon cake takes the browser to /search?q=lemon+cake. The question mark starts the query string, pairs are separated by &, and special characters are encoded (a space becomes +). URL Encoding explains those rules.

Because the data is in the address, a GET result can be bookmarked, shared and reloaded safely. Use GET for searches, filters, sorting and anything else that only reads data.

method="post"

With POST, the pairs travel in the body of the HTTP request instead of the URL. Use POST whenever submitting the form changes something: creating an account, sending a message, placing an order, uploading a file.

POST has practical advantages for those jobs:

  • Reloading the result page makes the browser warn before submitting again, which protects against double orders.
  • Passwords and personal details do not end up in the address bar, browser history or server logs.
  • There is no practical length limit, and files can be sent (with the right enctype, covered in Form Attributes).

POST is not encryption. Data in a POST body is just as readable as a query string to anyone who can see the traffic. What keeps form data private in transit is HTTPS. Always serve forms over HTTPS.

This example shows the query string a GET form would produce, using the browser's own URLSearchParams encoder:

Building a query string

Try typing characters such as &, ? or รฉ into the search box. The browser encodes them so the URL stays unambiguous.

Handling the submission in JavaScript

Sometimes you want to send the data without leaving the page at all, for example to show "Thanks!" in place. The pattern starts exactly like our demo: listen for submit, call preventDefault(), build a FormData. Then you send it yourself with fetch():

HTML
<script>
  const form = document.querySelector("#feedback");

  form.addEventListener("submit", async (event) => {
    event.preventDefault();
    const response = await fetch(form.action, {
      method: "POST",
      body: new FormData(form),
    });
    form.replaceWith(response.ok ? "Thanks for your feedback!" : "Something went wrong.");
  });
</script>

(This snippet is read-only: the sandbox has no server to talk to.)

Two habits make this approach robust:

  • Keep the real action and method on the form. If the script fails to load, the form still works the old-fashioned way.
  • Listen for submit, not for clicks on the button. The submit event fires for every way of submitting, including the Enter key, and it only fires after the browser's built-in validation has passed.

A few rules to remember

  • Forms cannot be nested. A <form> inside another <form> is ignored by the parser.
  • A page can have as many separate forms as it needs: a search box in the header and a contact form in the footer, for example.
  • Controls do not have to sit inside a <form> to be useful. A lone input can drive a script. But only controls that belong to a form are submitted with it (the form attribute, covered in Input Attributes, can connect a control that sits elsewhere).

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. A text input has an id but no name. What happens to its value when the form is submitted?

    Only controls with a name are included in the submitted name=value pairs. The id is for labels, CSS and scripts.
  2. 2. Which method suits a product filter page that people may want to bookmark?

    GET puts the pairs in the query string, so the result can be bookmarked, shared and reloaded. It is the right choice for actions that only read data.
  3. 3. What keeps a password private while it travels to the server?

    POST keeps the password out of the URL, and type="password" hides it on screen, but only HTTPS encrypts the data in transit.
  4. 4. Why listen for the form's submit event instead of the button's click event?

    People submit forms in several ways. The submit event catches all of them, and the browser fires it only when the form is valid.

Summary

  • A <form> groups controls; action says where the data goes and method says how.
  • On submit, the browser turns every named, enabled control into name=value pairs. Controls without a name are not sent.
  • GET puts the pairs in the URL: use it for searches and filters. POST puts them in the request body: use it for anything that changes data.
  • Only HTTPS protects data in transit; POST alone does not.
  • In JavaScript, listen for submit, call preventDefault(), and read the data with FormData.

Next up: Input Types, a tour of every kind of <input> the browser gives you for free.