13

HTML – Forms

Chapter 13 • Intermediate

30 min

Forms allow users to send data to a web server. They are essential for login, registration, search, and feedback.

The <form> Element

Wraps all form controls.

  • action: URL where data is sent.
  • method: HTTP method (GET or POST).

Important Form Controls

  1. <input>: The most versatile form element.
  • type="text": Single line text.
  • type="password": Hides characters.
  • type="email": Validates email format.
  • type="radio": Select one option from a group.
  • type="checkbox": Select multiple options.
  • type="date": Date picker.
  • type="submit": Button to send the form.
  1. <textarea>: Multi-line text input (for comments/messages).
  1. <select> and <option>: Dropdown list.
  1. <button>: Clickable button.

Labels and Accessibility

Always use <label> for accessibility.

  • Bind a label to an input using the for attribute (matching the input's id).
  • Clicking the label focuses the input.

Example:

html.js
<label for="username">Username:</label>
<input type="text" id="username" name="username">

Note: The name attribute is critical. Without a name, the input data will NOT be sent to the server when the form is submitted.

Attributes for Validation

  • required: The field must be filled.
  • placeholder: Hint text inside the field.
  • pattern: Regex for validation (advanced).

Suggested image prompt

"A clean registration form mockup labeled with HTML tags: <form>, <label>, <input type='text'>, <input type='password'>, <select>, and <button>."

Interview-style questions from this topic

  1. Why is the <label> tag important?
  2. What is the difference between method="GET" and method="POST"?
  3. How do you create a dropdown list in HTML?
  4. What does the required attribute do?

Hands-on Examples

Registration Form Example

<!DOCTYPE html>
<html>
<body>
  <h2>Register</h2>
  <form action="/submit-data">
    <div>
      <label for="name">Name:</label>
      <input type="text" id="name" name="name" required placeholder="John Doe">
    </div>
    <br>
    <div>
      <label for="email">Email:</label>
      <input type="email" id="email" name="email" required>
    </div>
    <br>
    <div>
      <label for="role">Role:</label>
      <select id="role" name="role">
        <option value="student">Student</option>
        <option value="teacher">Teacher</option>
      </select>
    </div>
    <br>
    <div>
      <label>Gender:</label>
      <input type="radio" id="male" name="gender" value="male">
      <label for="male">Male</label>
      <input type="radio" id="female" name="gender" value="female">
      <label for="female">Female</label>
    </div>
    <br>
    <button type="submit">Sign Up</button>
  </form>
</body>
</html>

This form collects name, email, role, and gender. It demonstrates usage of labels for accessibility, different input types, dropdowns, and basic validation with the required attribute.