Skip to main content

HTML Forms

HTML Forms Overview

Written by Updated HTML Forms Overview exercises

A form collects information from visitors and sends it somewhere: a login, a search, a contact message, an order. In HTML it is a form element around some fields and a button, plus two attributes that say where the data goes and how.

Basic Syntax

Everything starts with the <form> element. The fields inside it are mostly <input> elements, each with a <label>.

Forms Syntax

html

<form action="/samples/form_processor.php" method="post">
  <label for="name">Name:</label>
  <input type="text" id="name" name="username" required>
  
  <label for="email">Email:</label>
  <input type="email" id="email" name="useremail" required>
  
  <input type="submit" value="Submit">
</form>
  • action is the address that receives the data, usually a script on the server.
  • method="post" sends the data hidden in the request. Use get only for searches.
  • Each <label for="..."> matches the id of its field, so clicking the label focuses the field.
  • The name of each field is what the server receives the value under.
  • required stops the form from being sent while the field is empty.

Other Common Form Elements

Besides <input>, a form can contain:

ElementWhat it is for
<textarea>A box for several lines of text
<select>A drop-down list
<option>One choice in a drop-down
<button>A button to send or reset the form
<fieldset>A group of related fields
<legend>The title of a fieldset

All of them are described in HTML Form Elements, and the many kinds of input in input types.

Example with Different Controls

Form Example with Controls

html

<form action="/samples/form_processor.php" method="post">
  <fieldset>
    <legend>Contact Form</legend>

    <label for="fullname">Full Name:</label>
    <input type="text" id="fullname" name="fullname"><br><br>

    <label for="message">Message:</label>
    <textarea id="message" name="message"></textarea><br><br>

    <label for="gender">Gender:</label>
    <select id="gender" name="gender">
      <option value="male">Male</option>
      <option value="female">Female</option>
    </select><br><br>

    <button type="submit">Send</button>
  </fieldset>
</form>

What happens when you press Submit

  1. The browser checks the fields, for example that required fields are filled. See HTML Form Validation.
  2. It collects every field that has a name, as name and value pairs.
  3. It sends them to the action address, using the method.
  4. The server processes the data and sends back a new page, such as "Thanks, we got your message".

Without a server, a form cannot do anything with the data. JavaScript can also take over and send the data in the background, without reloading the page.

Browser Support

Chrome
Edge
Firefox
Safari
Opera
IE9+
YesYesYesYesYesYes

HTML Forms Overview exercises

A form with a button

Make a form with a submit button that says Send.

Result

Check your answer to see it here.