Tutorials HTML HTML Forms
Ch 10 / 40
Chapter 10 Beginner 10 min read HTML

HTML Forms — Collecting User Input

Forms are how websites talk back to users — login pages, registration forms, contact pages, search bars, and checkout flows all rely on HTML forms. In this chapter you'll master every form element, all input types, client-side validation, and accessibility best practices that professional developers follow.

What you'll learn
The <form> tag — action, method, and enctype
All HTML5 <input> types — text, email, password, number, and more
The <label> tag and why it is required for accessibility
<textarea>, <select>, checkbox, radio buttons
<fieldset> and <legend> for grouping fields
HTML5 built-in validation — required, pattern, min, max, minlength

What is an HTML Form?

An HTML form collects data from the user and sends it to a server for processing. The <form> element is the container — it defines where the data goes (action) and how it is sent (method). Everything the user fills in — text fields, dropdowns, checkboxes — lives inside this container.

HTML — Form Tag Anatomy
<form
  action="/submit-form"
  method="POST"
  enctype="multipart/form-data"
  novalidate
>
  <!-- form elements go here -->
</form>
action
The URL where form data is sent on submission. If omitted, the form submits to the current page URL. Example: action="/contact".
method
GET appends data to the URL (visible, bookmarkable — use for search). POST sends data in the request body (hidden, secure — use for login, registration, sensitive data).
enctype
Only needed when the form includes file uploads. Set to multipart/form-data to allow files to be sent correctly.
novalidate
Disables the browser's built-in HTML5 validation — useful when you want to handle validation entirely with JavaScript instead.
Live Form Preview — Course Enquiry
We'll never share your email with anyone.

The <label> & <input> Tags

Every input field must have a corresponding <label>. Labels are not just visual text — they are essential for accessibility: screen readers read the label aloud when the input is focused, and clicking the label focuses the input automatically.

HTML — Two ways to associate a label
<!-- Method 1: for + id (recommended) -->
<label for="username">Username</label>
<input
  type="text"
  id="username"
  name="username"
  placeholder="Enter your username"
>

<!-- Method 2: wrap input inside label -->
<label>
  Username
  <input type="text" name="username">
</label>
Always Link Labels to Inputs
The for attribute on <label> must match the id of the input exactly. An input without a linked label fails accessibility audits and violates WCAG standards. Using placeholder text alone is not a substitute for a label.

All HTML5 Input Types

The type attribute on <input> determines what kind of data the field accepts and what UI control the browser renders. Here are all the essential types:

type="text" Text
Single-line plain text input. The default type when type is omitted. Use for names, usernames, addresses.
type="password" Password
Masks input characters with dots or asterisks. Prevents shoulder-surfing. Never store passwords in plain text on the server.
type="number" Number
Numeric input with up/down spinner arrows. Supports min, max, and step attributes for range control.
type="tel" Telephone
Opens a numeric keypad on mobile devices. Does not validate format — use the pattern attribute to enforce a phone number format.
type="date" Date
Renders a date picker calendar widget. Value format is YYYY-MM-DD. Supports min and max to restrict selectable dates.
type="checkbox" Checkbox
A toggle that is either checked or unchecked. Use for multiple independent selections or a single agree/disagree toggle. The checked attribute pre-checks it.
type="radio" Radio Button
A mutually exclusive selection — only one radio button with the same name can be selected at a time. Use for single-choice options.
type="file" File Upload
Opens a file browser. Use the accept attribute to restrict file types (e.g. accept=".pdf,.jpg"). Requires enctype="multipart/form-data" on the form.
type="range" Slider
A drag slider for selecting a number in a range. Use min, max, and step to define the scale. Great for rating or budget filters.
type="color" Colour Picker
Opens the operating system colour picker. Returns the selected colour as a hex value (e.g. #e44d26). Great for theme customisers.
type="hidden" Hidden Field
Invisible to the user but submitted with the form. Used to pass data like CSRF tokens, user IDs, or page context that the user should not see or edit.
Not visible to users — value sent silently

<textarea> and <select>

Two essential form elements beyond basic <input>:

HTML — textarea and select
<!-- Multi-line text area -->
<label for="message">Message</label>
<textarea
  id="message"
  name="message"
  rows="5"
  cols="40"
  placeholder="Write your message here..."
  maxlength="500"
></textarea>

<!-- Dropdown select -->
<label for="course">Choose a Course</label>
<select id="course" name="course">
  <option value="">— Select —</option>
  <optgroup label="Web Development">
    <option value="html">HTML & CSS</option>
    <option value="js">JavaScript</option>
  </optgroup>
  <optgroup label="Programming">
    <option value="python">Python</option>
  </optgroup>
</select>
textarea vs input
Unlike <input>, <textarea> has a closing tag. Any text placed between opening and closing tags becomes the default value. Do not use the value attribute — it won't work on textareas.

<fieldset> and <legend>

<fieldset> groups related form fields together with a visual box. <legend> provides a title for that group. This is especially important for radio button groups and checkboxes — it tells screen readers what the group is about.

HTML — fieldset and legend
<form action="/enroll" method="POST">

  <fieldset>
    <legend>Personal Details</legend>

    <label for="fname">First Name</label>
    <input type="text" id="fname" name="fname">

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

  <fieldset>
    <legend>Preferred Learning Mode</legend>

    <label>
      <input type="radio" name="mode" value="online"> Online
    </label>
    <label>
      <input type="radio" name="mode" value="offline"> Offline
    </label>
  </fieldset>

  <button type="submit">Enroll Now</button>
</form>

HTML5 Built-in Form Validation

HTML5 provides powerful built-in validation attributes. The browser validates the form automatically when the submit button is clicked — no JavaScript required for basic validation.

Attribute Applied To Purpose Example
required Any input Field must not be empty — browser blocks submission if blank required
minlength text, password, textarea Minimum number of characters allowed minlength="8"
maxlength text, password, textarea Maximum number of characters allowed — hard stops input at limit maxlength="100"
min number, date, range Minimum acceptable value min="18"
max number, date, range Maximum acceptable value max="120"
pattern text, tel, email A regular expression the value must match — useful for phone numbers and postal codes pattern="[0-9]{10}"
step number, range, date Legal number intervals — e.g. step="5" only allows 0, 5, 10, 15... step="0.5"
disabled Any input Disables the field — not submitted with the form. Greyed out visually. disabled
readonly text, textarea User cannot edit the value but it IS submitted with the form readonly
autocomplete Any input Controls browser autofill — on (default), off, or a specific hint like "email" autocomplete="email"
HTML — Validation attributes in action
<form action="/register" method="POST">

  <label for="uname">Username</label>
  <input
    type="text"
    id="uname"
    name="username"
    required
    minlength="3"
    maxlength="20"
    pattern="[a-zA-Z0-9_]+"
    placeholder="3–20 chars, letters & numbers only"
  >

  <label for="pwd">Password</label>
  <input
    type="password"
    id="pwd"
    name="password"
    required
    minlength="8"
    autocomplete="new-password"
  >

  <label for="age">Age</label>
  <input
    type="number"
    id="age"
    name="age"
    min="18"
    max="99"
    required
  >

  <button type="submit">Create Account</button>
</form>

Button Types — <button>

HTML provides three button types. Choosing the wrong type is a common mistake — especially inside forms.

type="submit"
Submits the form to the server — the default type for buttons inside a <form>. If you omit the type attribute, the browser treats it as submit. Can unexpectedly submit forms if placed inside one without intent.
type="reset"
Resets all form fields to their default values — clears user input. Use with caution: users rarely expect or want a reset button and often click it by mistake.
type="button"
Does nothing by default — only fires JavaScript event listeners. Use whenever you want a button that triggers a JS action without submitting the form. Always prefer this over submit when you're handling the action with JavaScript.
HTML — All button types
<!-- Submits the form -->
<button type="submit">Send Message</button>

<!-- Resets all fields -->
<button type="reset">Clear Form</button>

<!-- Does nothing — attach a JS listener -->
<button type="button" onclick="handleClick()">Preview</button>

Common Mistakes — Do's & Don'ts

These are the most frequent form mistakes beginners make:

Do — Correct
<!-- Always link labels to inputs -->
<label for="email">Email</label>
<input type="email"
       id="email"
       name="email"
       required>

<!-- Use type="button" for JS actions -->
<button type="button"
        onclick="openModal()">
  Preview
</button>
Don't — Wrong
<!-- Input without a label (inaccessible) -->
<input type="text"
       placeholder="Email">

<!-- Missing type — defaults to submit -->
<button onclick="openModal()">
  Preview  ← submits form!
</button>

<!-- Placeholder as only label -->
<input type="email"
       placeholder="Enter email">
Placeholder ≠ Label
Placeholder text disappears as soon as the user starts typing — making it impossible to know what the field requires. Screen readers often skip placeholder text entirely. Always use a visible <label>. A placeholder is only a hint about the expected format or example value.

Complete Example — Registration Form

Here is a full, valid, accessible registration form combining everything covered in this chapter:

HTML — Complete Registration Form
<form action="/register" method="POST">

  <fieldset>
    <legend>Personal Information</legend>

    <label for="fname">First Name</label>
    <input type="text" id="fname" name="first_name"
           required minlength="2" autocomplete="given-name">

    <label for="email">Email Address</label>
    <input type="email" id="email" name="email"
           required autocomplete="email">

    <label for="pwd">Password</label>
    <input type="password" id="pwd" name="password"
           required minlength="8" autocomplete="new-password">
  </fieldset>

  <fieldset>
    <legend>Course Preference</legend>

    <label for="course">Choose Course</label>
    <select id="course" name="course" required>
      <option value="">— Select —</option>
      <option value="webdev">Web Development</option>
      <option value="python">Python</option>
    </select>

    <!-- Radio group for learning mode -->
    <p>Mode:</p>
    <label><input type="radio" name="mode" value="online"  required> Online</label>
    <label><input type="radio" name="mode" value="offline"> Offline</label>
  </fieldset>

  <label for="msg">Message (optional)</label>
  <textarea id="msg" name="message"
             rows="4" maxlength="300"></textarea>

  <label>
    <input type="checkbox" name="terms" required>
    I agree to the terms and conditions
  </label>

  <button type="submit">Create Account</button>

</form>

Try It Yourself

Edit the form below and click Open in Editor to test it live in full screen — including the HTML5 validation by clicking the submit button with empty fields.

Live Editor
✎ Editor
👁 Preview
Try This
Click Send Enquiry in the preview without filling any fields — the browser fires HTML5 validation errors automatically. Then try entering an invalid phone number (e.g. "123") and see the pattern validation reject it. No JavaScript needed!
Free Resource
HTML5 Cheat Sheet — All Tags & Attributes
One printable PDF covering every HTML form element, all input types, validation attributes, and accessibility rules.
Download PDF
Featured Course — Enroll Now
Modern Web Development With AI
Master HTML, CSS, JavaScript, React, and Node.js in one industry-ready curriculum with real projects and placement support.
120+
Chapters
40 hrs
Content
10
Projects
4.9 ⭐
Rating
HTML5 CSS3 JavaScript React.js Node.js MongoDB AI Tools

Quick Check — Chapter 10

Expand each question to check your understanding before moving on to the multiple choice quiz below.

Questions & Answers
GET appends the form data to the URL as query parameters — for example /search?q=html+tutorial. The data is visible in the browser address bar, can be bookmarked, and is stored in browser history. Use GET for search forms and non-sensitive requests. POST sends data in the HTTP request body, invisible in the URL. Use POST for login, registration, payment, and any form that submits sensitive or large amounts of data. POST is also required when uploading files.
No — placeholder text is not a substitute for a label. Placeholders disappear the moment the user starts typing, making it impossible to remember what the field requires. Screen readers often skip placeholder text or read it inconsistently. A properly linked <label> is always visible, is read aloud by screen readers when the input is focused, and clicking the label focuses the input — improving usability. Using only placeholders fails WCAG accessibility standards and makes forms very difficult for people with cognitive disabilities.
Both prevent the user from editing the field, but they behave differently on submission. A disabled input is excluded from form submission — its value is never sent to the server. It also appears greyed out and cannot be focused. A readonly input is submitted with the form — its value is sent to the server — but the user cannot modify it. Use readonly when you want to show the user a pre-filled value that must be submitted unchanged (like a hidden order reference), and disabled when the field is truly inactive and irrelevant to the current form submission.
Checkboxes are independent toggles — users can select multiple checkboxes at once. Each checkbox has its own name or shares a name as an array. Use for "Select all that apply" scenarios like choosing skills or interests. Radio buttons are mutually exclusive — only one radio button in a group (those sharing the same name) can be selected at a time. Selecting one deselects the others. Use for "Choose one" scenarios like payment method or learning mode.
The default type for any <button> inside a <form> is submit. This means any button without an explicit type attribute will submit the form when clicked — even if that was not your intent. This is a very common bug: a developer adds <button onclick="openModal()">Preview</button> expecting it to open a modal, but it submits the form instead. Always write type="button" for non-submit buttons, type="submit" for submit buttons, and type="reset" for reset buttons.
enctype="multipart/form-data" is only required when the form includes a file upload (type="file"). The default encoding (application/x-www-form-urlencoded) URL-encodes the form data as text — it cannot handle binary file data. multipart/form-data splits the form data into multiple parts, allowing binary files to be transmitted alongside text fields. Without it, the file will not be sent correctly to the server. Also note: file uploads always require method="POST" — you cannot upload files via GET.
Multiple Choice Questions
MCQ 1 of 4
Which HTML attribute links a <label> to an <input>?
MCQ 2 of 4
Which input type opens the operating system's colour picker?
MCQ 3 of 4
Which validation attribute makes a field mandatory — blocking form submission if left empty?
MCQ 4 of 4
What is the default type of a <button> element placed inside a <form>?
Chapter Summary
  • The <form> tag defines where (action) and how (method) data is sent. Use POST for sensitive data; GET for search/filter. Add enctype="multipart/form-data" only for file uploads.
  • Every input must have a linked <label> using for matching the input's id. Placeholder text is not a label substitute.
  • HTML5 provides many type values — text, email, password, number, tel, date, checkbox, radio, file, range, color, hidden. Each triggers the right keyboard on mobile.
  • <textarea> is for multi-line text (has a closing tag). <select> + <option> creates a dropdown. Use <optgroup> to group options.
  • <fieldset> + <legend> groups related fields semantically — essential for radio button groups.
  • HTML5 validation: required, minlength, maxlength, min, max, pattern — all validated by the browser with no JavaScript needed.
  • Always specify type on <button>. Default is submit — causing accidental form submissions if omitted on non-submit buttons.
~10 min read
Beginner level
Chapter 10 of 40

Rate Us on Google

4.8 / 5
Enjoying this tutorial?
If this tutorial helped you, a 5-star Google review means a lot. It helps other learners discover our free content and motivates us to keep improving.
500+ Reviews (Target)
Write a Google Review
Join WhatsApp Channel