Lesson 15 +10 XP

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>.

Code

html
<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: &lt;input&gt;

&lt;input&gt; is the workhorse. Its type decides what it looks like.

Code

html
<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.

Code

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

Labels: &lt;label&gt;

Every input should have a &lt;label&gt;. The label connects to the input with the for attribute (matching the input's id).

Code

html
<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: &lt;button&gt;

&lt;button&gt; is the clickable button. The text goes inside.

Code

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

Types:

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

Grouping: &lt;fieldset&gt; and &lt;legend&gt;

  • &lt;fieldset&gt;: draws a box around a group of inputs.
  • &lt;legend&gt;: the title of that box.
Code

html
<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 &lt;label&gt;.

TL;DR

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