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
<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>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
<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>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.
Exercise 1Solved
Make the browser check that this field holds a valid email address.
<input type="" name="email">Exercise 2Solved
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">The label's attribute must match the input's
id.Exercise 3Solved
Stop the form from being sent while this field is empty.
<input type="text" name="fullname" >
Finish the practice to complete this lesson.
Sign in to keep your progress on any device.