Creating Forms in HTML

Hi, I'm Ahbab. In this article, I'll teach you how to create forms in HTML, including input fields, buttons, and best practices for designing user-friendly forms.

What is the <form> Element?

The <form> element is used to collect user input. It can include various input types, such as text fields, checkboxes, radio buttons, and submit buttons.

Example: Basic Form

<form action="/submit" method="post">
    <label for="name">Name:</label>
    <input type="text" id="name" name="name" required>
    <br>
    <label for="email">Email:</label>
    <input type="email" id="email" name="email" required>
    <br>
    <button type="submit">Submit</button>
</form>
        

This example demonstrates a simple form with text and email input fields, along with a submit button.

Common Input Types

Example: Advanced Form

<form action="/register" method="post">
    <fieldset>
        <legend>Registration Form</legend>
        <label for="username">Username:</label>
        <input type="text" id="username" name="username" required>
        <br>
        <label for="password">Password:</label>
        <input type="password" id="password" name="password" required>
        <br>
        <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>
        <br>
        <label for="terms">Accept Terms:</label>
        <input type="checkbox" id="terms" name="terms" required>
        <br>
        <button type="submit">Register</button>
    </fieldset>
</form>
        

This example includes a registration form with text, password, radio buttons, and a checkbox.

Best Practices for Forms

Practice: Try It Yourself

  1. Project: Contact Form
    Create a contact form with fields for name, email, subject, and message. Add a submit button.
  2. Project: Survey Form
    Build a survey form with multiple-choice questions using radio buttons and checkboxes.

Continue Learning

Quick Check

Which HTML element is used to label an input for accessibility?