HTML Forms

HTML Forms

An HTML form is a key element in web development, enabling users to input and send data to a server. Since HTML itself is open-source and not copyrighted, creating and using an HTML form does not raise copyright issues as long as the code is original or derived from open resources.


Here are the essential elements and steps for constructing an HTML form:

1. Form Structure

  • <form> Tag: Encloses the form elements, indicating its start and end.
  • action Attribute: Determines the destination URL for form submission.
  • method Attribute: Specifies the HTTP method used to send data(GET or POST).

Example:

  <form action="/submit-form" method="POST">
    <!-- Form content goes here -->
  </form> 

2. Input Fields

HTML provides several input types to collect data:

  • Text Input:
      <label for="name">Name:</label>
      <input type="text" id="name" name="name" required>
                      
  • Email Input:
      <label for="email">Email:</label>
      <input type="email" id="email" name="email" required>
                      
  • Password Input:
      <label for="password">Password:</label>
      <input type="password" id="password" name="password" required>   
                      
  • Checkbox:
      <label>
      <input type="checkbox" name="subscribe" value="yes"> Subscribe to newsletter
      </label>     
                      
  • Radio Buttons:
    <label>
    <input type="radio" name="gender" value="male"> Male
    </label>
    <label>
      <input type="radio" name="gender" value="female"> Female
    </label>      
                      
  • Dropdown:
    <label for="country">Country:</label>
    <select id="country" name="country">
      <option value="us">United States</option>
      <option value="ca">Canada</option>
      <option value="uk">United Kingdom</option>
    </select>             
                      

3. Submit Button

A button to send form data:

<button type="submit">Submit</button>   
            

4. Form Validation

Add basic validation using HTML attributes:

  • required: Ensures the field is not empty.
  • pattern: Specifies a regex for custom validation.
  • min, max: Set range limits for numerical inputs.

Example:

  <input type="number" name="age" min="18" max="100" required>       
              

5. Accessibility Best Practices

  • Use <label> tags for each input for better usability.
  • Add placeholders sparingly, as they do not replace labels.
  • Include aria-* attributes for dynamic forms if necessary.

Previous Next