Lesson 15 +10 XP

Forms - The Basics

Forms: The Basics

Forms let visitors type things, pick options, and press buttons. Logging in, buying stuff, leaving comments: that's all forms!

The <form> element

Everything for one form goes inside <form>.

<form action="/signup" method="post">
  ...
</form>
  • action: where the form's data goes (the server address).
  • method: how the data travels. get puts it in the URL (visible), post sends it hidden (better for passwords and sensitive data).### Inputs: <input>

<input> is the workhorse. Its type decides what it looks like.

<input type="text" name="username" placeholder="Your name">

The name attribute

Every input needs a name. It's like the label on a box when the data is sent.

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

Labels: <label>

Every input should have a <label>. The label connects to the input with the for attribute (matching the input's id).

<label for="email">Email address</label>
<input type="email" id="email" name="email">

Labels are super important: clicking the label focuses the input, and screen readers announce the label!

Buttons: <button>

<button> is the clickable button. The text goes inside.

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

Types:

  • submit: sends the form (default).
  • reset: clears the form.
  • button: does nothing by itself (used with JavaScript).

Grouping: <fieldset> and <legend>

  • <fieldset>: draws a box around a group of inputs.
  • <legend>: the title of that box.
<fieldset>
  <legend>Shipping address</legend>
  <label for="street">Street</label>
  <input type="text" id="street" name="street">
</fieldset>

Placeholder vs label

placeholder shows grey example text that disappears when you type. It's a hint, NOT a replacement for a <label>.

TL;DR

  • <form action="..." method="..."> wraps a form.
  • <input type="..." name="..."> is a field.
  • <label for="input-id"> names a field.
  • <button type="submit"> sends the form.
  • <fieldset>/<legend> group and title related fields.
  • Always use labels, and give inputs a name.