Home HTML Intermediate Lesson 2 — Forms

1. Introduction

Forms are how users send data to a website — signing up, logging in, buying a product, searching, leaving a comment. Forms are everywhere.

HTML forms consist of a <form> container and various input elements inside it. Understanding forms is essential because they are the primary way users interact with web applications.

2. Theory

The <form> Element

<form action="/submit" method="POST">
  <!-- inputs go here -->
</form>
AttributeValuesMeaning
actionURLWhere to send the form data when submitted
methodGET or POSTHow to send the data
novalidateDisables browser's built-in validation (for testing)
autocompleteon / offAllow browser to auto-fill form fields

GET vs POST

GETPOST
Data locationIn the URL: ?name=John&age=25In the request body — not visible in URL
Use forSearch forms, filters (bookmarkable)Login, registration, payments (sensitive data)
Data limit~2000 charactersNo practical limit
SecurityData visible in URL and browser historyData not stored in browser history

Form Labels — Critical for Accessibility

Every input must have a <label>. There are two ways to associate them:

<!-- Method 1: label wraps the input -->
<label>
  Full Name
  <input type="text" name="fullname">
</label>

<!-- Method 2: for attribute matches input id -->
<label for="email">Email Address</label>
<input type="email" id="email" name="email">

Clicking the label focuses the associated input — this is especially important for checkboxes and radio buttons with small click targets.

The <input> Element

The most versatile form element — its type attribute determines what it is:

typeWhat it Creates
textSingle-line text field
emailEmail field (validates @ symbol)
passwordPassword field (hides characters)
numberNumber field with up/down arrows
telPhone number field (shows numeric keyboard on mobile)
urlURL field (validates http/https)
dateDate picker
checkboxTick box — yes/no choice
radioRound button — one choice from a group
fileFile upload button
submitSubmit button
resetResets all fields to default
hiddenInvisible field — carries data the user does not see
rangeSlider
colorColour picker
searchSearch box (may show X to clear on some browsers)

Input Validation Attributes

AttributeExampleWhat It Does
requiredrequiredField must be filled in before submission
minlengthminlength="6"Minimum number of characters
maxlengthmaxlength="100"Maximum number of characters
minmin="18"Minimum value (for number/date inputs)
maxmax="120"Maximum value
patternpattern="[A-Za-z]{3,}"Regex pattern the value must match
placeholderplaceholder="Enter email"Hint text inside the field (disappears on typing)
disableddisabledField cannot be interacted with
readonlyreadonlyCan be read but not changed
autofocusautofocusAutomatically focuses this field when page loads

Other Form Elements

<!-- Multi-line text area -->
<textarea name="message" rows="5" cols="40"></textarea>

<!-- Drop-down select -->
<select name="country">
  <option value="">Choose a country...</option>
  <option value="uk">United Kingdom</option>
  <option value="us">United States</option>
</select>

<!-- Button (preferred over input type="submit") -->
<button type="submit">Send Message</button>

<!-- Fieldset + Legend: groups related inputs -->
<fieldset>
  <legend>Personal Information</legend>
  <!-- inputs here -->
</fieldset>

3. Real World Example

A registration form on any website uses the same fundamental elements you are learning here: text fields for name, email input with validation, password field that hides characters, a terms checkbox that is required, and a submit button. Master this lesson and you can build that form from scratch.

4. Code Example

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Contact Form</title>
</head>
<body>

<h1>Contact Us</h1>

<form action="/contact" method="POST">

  <fieldset>
    <legend>Your Details</legend>

    <label for="name">Full Name *</label>
    <input type="text" id="name" name="name"
           placeholder="Jane Smith"
           required
           minlength="2"
           maxlength="80">

    <label for="email">Email Address *</label>
    <input type="email" id="email" name="email"
           placeholder="jane@example.com"
           required>

    <label for="phone">Phone (optional)</label>
    <input type="tel" id="phone" name="phone"
           placeholder="+44 7700 900123">
  </fieldset>

  <fieldset>
    <legend>Your Message</legend>

    <label for="subject">Subject *</label>
    <select id="subject" name="subject" required>
      <option value="">Choose a subject...</option>
      <option value="general">General Enquiry</option>
      <option value="support">Technical Support</option>
      <option value="sales">Sales</option>
    </select>

    <label for="message">Message *</label>
    <textarea id="message" name="message"
              rows="6"
              placeholder="Write your message here..."
              required
              minlength="20"></textarea>
  </fieldset>

  <label>
    <input type="checkbox" name="newsletter">
    Subscribe to our newsletter
  </label>

  <label>
    <input type="checkbox" name="terms" required>
    I agree to the <a href="/terms">Terms & Conditions</a> *
  </label>

  <button type="submit">Send Message</button>
  <button type="reset">Clear Form</button>

</form>

</body>
</html>

5. Code Breakdown

CodeWhat It Does
<form action="/contact" method="POST">Form sends data via POST to /contact when submitted
<fieldset> + <legend>Groups related inputs with a visible border and title
<label for="name">Label linked to the input with id="name". Clicking the label focuses the input.
requiredBrowser blocks form submission if this field is empty
minlength="2"At least 2 characters required — browser validates automatically
type="email"Browser validates email format (must contain @) before submission
type="tel"No browser validation but shows numeric keyboard on mobile
<select>Drop-down list. First option with empty value forces a selection
<textarea rows="6">Multi-line text input. rows sets the visible height
<button type="submit">Submits the form when clicked
<button type="reset">Clears all form fields back to default values

6. Common Mistakes

Mistake 1 — Inputs without labels

Every input needs a <label>. Placeholder text is not a label — it disappears when the user starts typing. Missing labels break accessibility.

Mistake 2 — id and for attributes not matching

The label's for attribute must exactly match the input's id: <label for="email"> + <input id="email">. A mismatch breaks the association.

Mistake 3 — Using GET for sensitive forms

Never use method="GET" for login forms, payment forms, or any form with personal data — the data appears in the browser URL and history. Use POST.

7. Best Practices

Always link labels to inputs — use for/id pairing or wrap inputs inside labels.
Use the correct input typetype="email" gives free validation, type="tel" gives a better mobile keyboard.
Use required, minlength, and other validation attributes — browser-native validation is free and accessible.
Use <button> instead of <input type="submit"> — buttons can contain HTML (icons, formatted text) and are more flexible to style.
Mark required fields visually — conventionally with an asterisk (*) and a note at the top of the form.

8. Practice Exercise

Build a registration form for a fictional website. Include:

  • Username (text, required, minlength 3)
  • Email (email type, required)
  • Password (password type, required, minlength 8)
  • Date of birth (date type)
  • Country (select with at least 5 options)
  • Profile bio (textarea)
  • Terms agreement checkbox (required)
  • Newsletter checkbox (optional)
  • Submit and Reset buttons
  • Use fieldsets to group related fields

9. Assignment

Build a job application form. It should collect: full name, email, phone, position applied for (select dropdown), years of experience (number, min 0, max 50), cover letter (textarea, minlength 100), CV upload (file input), LinkedIn profile URL, and a declaration checkbox. Use proper labels, fieldsets, validation, and both a submit and reset button.

10. Interview Questions

Q1: What is the difference between GET and POST in forms?

Answer: GET appends form data to the URL as query parameters — visible in the browser address bar and stored in history. Use GET for search forms (results should be bookmarkable). POST sends data in the HTTP request body — not visible in the URL. Use POST for login, registration, payment, or any form handling sensitive data.

Q2: Why are labels important in forms?

Answer: Labels serve three purposes: 1) They tell users what to enter in each field. 2) Clicking a label focuses its associated input, making small inputs (checkboxes, radio buttons) easier to click. 3) Screen readers read labels to announce input fields — without labels, visually impaired users cannot use the form.

Q3: What is the difference between disabled and readonly?

Answer: Both prevent editing. disabled makes the field completely inactive — users cannot interact with it and its value is NOT submitted with the form. readonly prevents editing but the field is still focusable and its value IS submitted. Use readonly for pre-filled values you want included in submission, disabled for fields that should be excluded.

Q4: What is the purpose of the name attribute on inputs?

Answer: The name attribute is the key used when form data is submitted. If an input has name="email" and the user types "john@example.com", the server receives email=john@example.com. Without a name attribute, the field's value is not submitted with the form at all.