HTML forms are essential for collecting user input on a website. They allow users to enter information like names, email addresses, passwords, or upload files. These inputs can then be sent to a server for processing, such as logging in, signing up, or submitting feedback.
Basic Syntax
An HTML form is created using the <form> element, which wraps around input fields, buttons, and other controls.
<form action="submit_form.php" method="post">
<label for="name">Name:</label>
<input type="text" id="name" name="username" required>
<label for="email">Email:</label>
<input type="email" id="email" name="useremail" required>
<input type="submit" value="Submit">
</form>
Explanation
<form>— The container element for all form controls.- action — Specifies the URL where form data will be sent for processing.
- method — Determines how data is sent:
GETappends data to the URL (used for search or simple data).POSTsends data securely in the request body (used for login, signup, etc.).<label>— Describes an input field for better accessibility.<input>— Used for collecting data such as text, email, password, etc.<input type="submit">— Creates a button to submit the form.
Other Common Form Elements
HTML forms can contain several elements besides <input>:
| Element | Description |
|---|---|
<textarea> | Multi-line text input field. |
<select> | Dropdown menu for multiple options. |
<option> | Defines each choice within a dropdown. |
<button> | Adds custom buttons for submitting or resetting forms. |
<fieldset> | Groups related form fields together. |
<legend> | Defines a title for a fieldset group. |
Example with Different Controls
<form action="/submit" method="post">
<fieldset>
<legend>Contact Form</legend>
<label for="fullname">Full Name:</label>
<input type="text" id="fullname" name="fullname"><br><br>
<label for="message">Message:</label>
<textarea id="message" name="message"></textarea><br><br>
<label for="gender">Gender:</label>
<select id="gender" name="gender">
<option value="male">Male</option>
<option value="female">Female</option>
</select><br><br>
<button type="submit">Send</button>
</fieldset>
</form>
How Forms Work
When the user clicks the Submit button:
- Browser gathers all field values.
- Sends data to the server via the
actionURL. - The server processes the input (e.g., saves it, emails it, or validates it).
- The user receives a response (success or error).
Conclusion
HTML forms are the foundation of user interaction on the web. Whether it’s logging in, submitting a comment, or making a purchase — forms make it possible. As we move ahead, you’ll learn about form elements, input types, attributes, and how to validate user input.