Section 16: Form Structure, Action, Method and Submission
Learning Objectives
- Understand why HTML forms are used.
- Learn the form, input, label, button and textarea elements.
- Understand action, method, enctype and autocomplete.
- Learn how browsers submit form data.
1. What Is an HTML Form?
An HTML form collects information from users. Common examples include login forms, registration forms, contact forms, search boxes and checkout forms.
2. Basic Form Structure
<form action="/register" method="post">
<label for="name">Full 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">Register</button>
</form>The form element groups controls and defines how their data is submitted. The label describes each field, and the button submits the form.
3. The action Attribute
The action attribute specifies the URL that receives the submitted form data. If it is omitted, the browser normally submits to the current document URL.
<form action="/contact" method="post">
...
</form>The URL must be handled by a server or application route. HTML alone does not store the data in a database or send an email.
4. GET vs POST
| GET | POST |
|---|---|
| Usually used to retrieve or search for information. | Usually used to submit or change information. |
| Form data is commonly included in the URL query string. | Form data is sent in the request body. |
| Can be bookmarked and shared with its query parameters. | Not normally represented by the URL alone. |
| Do not use for sensitive information. | Still requires HTTPS and server-side security. |
<!-- Search form -->
<form action="/search" method="get">
<input type="search" name="q" placeholder="Search products">
<button type="submit">Search</button>
</form>
<!-- Registration form -->
<form action="/register" method="post">
<input type="text" name="username" required>
<button type="submit">Create Account</button>
</form>5. The name Attribute
The name attribute identifies a control in submitted form data. A field with an id but no name is generally not included in the form submission.
<input type="text" id="username" name="username">6. The enctype Attribute
enctype defines how POST form data is encoded.
- application/x-www-form-urlencoded: the default for ordinary form submissions.
- multipart/form-data: required when a form uploads files.
- text/plain: a rarely used format, generally unsuitable for production forms.
<form action="/upload" method="post" enctype="multipart/form-data">
<label for="document">Upload document:</label>
<input type="file" id="document" name="document">
<button type="submit">Upload</button>
</form>7. Autocomplete
The autocomplete attribute tells the browser whether it may suggest previously entered information.