Chapter 4: Forms and User Input

Static pages are great for reading, but if you want your website to do something—like allow a user to sign up, search for content, or send you a message—you need Forms. An HTML form is a section of a document containing normal content, markup, and special elements called "controls" (checkboxes, radio buttons, menus) that allow the user to interact with your site.

1. The Form Structure

The <form> element is the container for all user input controls. It requires two main attributes: action (where the data should be sent) and method (how the data should be sent, typically GET or POST).

<form action="/submit-data" method="POST">
    <label for="name">Name:</label>
    <input type="text" id="name" name="user_name">
    <button type="submit">Submit</button>
</form>

Pro Tip: Always use the <label> tag and link it to your <input> using the for and id attributes. This makes your form accessible to screen readers and allows users to click the text to focus the input field.

2. Common Input Types

HTML5 brought us a wide variety of input types that help the browser validate data automatically:

3. Understanding GET vs. POST

When submitting a form, you choose between two primary methods:

4. Advanced Controls

For more complex input, you can use the <textarea> tag for multi-line comments or the <select> tag to create a dropdown menu of options. These elements add significant depth to the types of data you can collect from your visitors.

Common Beginner Mistakes

Try It Yourself

  1. Create a simple contact form with fields for "Name," "Email," and "Message."
  2. Add a "Submit" button to the form.
  3. Add a radio button group so the user can choose their preferred contact method (e.g., Email or Phone).

Common Input Types

HTML5 introduced many specialized input types that provide better validation and mobile keyboards automatically, without any extra JavaScript.

<input type="email" placeholder="you@example.com">
<input type="date">
<input type="number" min="1" max="10">
<input type="checkbox" id="subscribe">
<label for="subscribe">Subscribe to newsletter</label>

Basic Form Validation

Adding the required attribute prevents a form from submitting until that field is filled in, giving you free client-side validation.

<input type="text" name="username" required minlength="3">