HTMLLesson 7 of 10Jump to practice

Forms

Collect input from visitors with form, input, label and button.

Forms are how websites take input: logging in, searching, signing up, placing an order.

The parts of a form

A sign-up form
Open in editor
<form id="signup">
<p>
  <label for="name">Your name</label><br>
  <input id="name" name="name" type="text" required>
</p>
<p>
  <label for="email">Email</label><br>
  <input id="email" name="email" type="email" placeholder="you@example.com" required>
</p>
<button type="submit">Sign up</button>
</form>
<p id="message"></p>

<script>
// Real forms send data to a server. This one just shows a message.
document.getElementById("signup").addEventListener("submit", function (event) {
  event.preventDefault();
  const name = document.getElementById("name").value;
  document.getElementById("message").textContent = "Thanks, " + name + "!";
});
</script>
Result

Press Sign up with the fields empty, then with a broken email like abc. The browser checks them for you, because of required and type="email".

Element or attribute What it does
<form> Wraps the fields that are sent together
<input> A single field. Its type decides what kind
<label for="..."> The field’s name, tied to the input with the same id
name The key the value is sent under, like email=you@example.com
<button type="submit"> Sends the form

More kinds of input

Other input types
Open in editor
<form>
<p><label for="age">Age</label>
   <input id="age" type="number" min="1" max="120"></p>

<p><label for="dob">Date of birth</label>
   <input id="dob" type="date"></p>

<p><label for="color">Favorite color</label>
   <input id="color" type="color" value="#0b7a75"></p>

<p><label for="division">Division</label>
   <select id="division">
     <option>Chicago</option>
     <option>Houston</option>
     <option>Seattle</option>
   </select></p>

<p><input id="terms" type="checkbox">
   <label for="terms">I agree to the rules</label></p>

<p><label for="msg">Message</label><br>
   <textarea id="msg" rows="3" cols="30"></textarea></p>
</form>
Result

On a phone, type="email" and type="number" also bring up a keyboard that suits the field.

Practice

Check what you just learned. Fill in the missing code, then answer the quiz.

  1. Exercise 1

    Make the browser check that this field holds a valid email address.

    <input type="" name="email">

  2. Exercise 2

    Connect the label to the input, so clicking the label puts the cursor in the field.

    <label ="city">City</label>
    <input id="city" name="city">

  3. Exercise 3

    Stop the form from being sent while this field is empty.

    <input type="text" name="fullname" >

Quiz: 3 questions

1. Why should every input have a <label>?
2. Which input type hides what you type?
3. What does placeholder="e.g. Marcus" do?

Finish the practice to complete this lesson.