HTML forms are essential components of interactive websites, allowing users to input data and submit information. This guide will walk you through a practical example of creating an HTML form.
Let's start with a simple form that collects a user's name and email address:
<form action="/submit-form" method="post">
<label for="name">Name:</label>
<input type="text" id="name" name="name" required>
<label for="email">Email:</label>
<input type="email" id="email" name="email" required>
<button type="submit">Submit</button>
</form>
This example demonstrates the basic structure of an HTML form. The <form>
element wraps all form controls, while <label>
and <input>
elements create the individual form fields.
The <form>
tag includes two important attributes:
For more details on form attributes, check out the HTML Form Attributes guide.
HTML5 introduced various input types to enhance form functionality and user experience. Here's an expanded example:
<form action="/submit-form" method="post">
<label for="name">Name:</label>
<input type="text" id="name" name="name" required>
<label for="email">Email:</label>
<input type="email" id="email" name="email" required>
<label for="birthdate">Birthdate:</label>
<input type="date" id="birthdate" name="birthdate">
<label for="age">Age:</label>
<input type="number" id="age" name="age" min="0" max="120">
<label for="website">Website:</label>
<input type="url" id="website" name="website">
<button type="submit">Submit</button>
</form>
This example showcases various input types, including text, email, date, number, and URL. Each type provides built-in validation and appropriate user interfaces on supporting browsers.
Forms can include various elements beyond simple text inputs. Here are some common ones:
Learn more about these elements in the HTML Form Elements guide.
<fieldset>
and <legend>
tags.required
attribute for mandatory fields.HTML forms are powerful tools for collecting user input. By combining various form elements and following best practices, you can create user-friendly and efficient web forms. Remember to style your forms with CSS and enhance them with JavaScript for a complete user experience.
For more advanced form features, explore HTML5 Forms and HTML Form Attributes.