HTML Forms: An Introduction
Forms are created with the <form>
element and are used to collect user input:
<form action="/submit" method="post">
<!-- Form controls go here -->
<button type="submit">Submit</button>
</form>
Key purposes of forms:
- User registration/login
- Contact forms
- Search functionality
- Data collection
Common Form Elements and Tags
Essential form elements:
Element | Description | Example |
---|---|---|
<input> | Most versatile form control | <input type="text"> |
<textarea> | Multi-line text input | <textarea rows="4"></textarea> |
<select> | Dropdown list | <select><option>Option 1</option></select> |
<button> | Clickable button | <button type="submit">Send</button> |
<label> | Label for form controls | <label for="name">Name:</label> |
HTML Form Attributes (action, method, etc.)
Key form attributes:
action
- Where to send form datamethod
- HTTP method (GET/POST)enctype
- Encoding type for file uploads
target
- Where to display responseautocomplete
- Enable/disable autofillnovalidate
- Disable validation
Example with common attributes:
<form action="/process" method="post"
enctype="multipart/form-data" target="_blank">
<!-- Form content -->
</form>
All HTML Input Types Explained
Type | Description | Example |
---|---|---|
text | Single-line text input | <input type="text"> |
password | Masked input | <input type="password"> |
email | Email validation | <input type="email"> |
number | Numeric input | <input type="number"> |
date | Date picker | <input type="date"> |
file | File upload | <input type="file"> |
checkbox | Multiple selection | <input type="checkbox"> |
radio | Single selection | <input type="radio"> |
range | Slider control | <input type="range"> |
color | Color picker | <input type="color"> |
Input-Specific Attributes (placeholder, required, etc.)
Common input attributes:
placeholder
- Hint textrequired
- Mandatory fieldreadonly
- Read-only fielddisabled
- Disabled field
maxlength
- Character limitmin/max
- Value rangepattern
- Regex validationautofocus
- Auto focus
Example with multiple attributes:
<input type="email"
id="user-email"
name="email"
placeholder="your@email.com"
required
maxlength="100"
pattern="[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}$">
Customizing Input with Attributes
Advanced customization options:
Styling Attributes
class
- For CSS stylingstyle
- Inline stylessize
- Visible width
Behavior Attributes
autocomplete
- Form autofillform
- Associate with formlist
- Datalist reference
Example with datalist:
<input list="browsers" name="browser">
<datalist id="browsers">
<option value="Chrome">
<option value="Firefox">
<option value="Safari">
</datalist>
Example with custom validation:
<input type="text"
id="username"
name="username"
pattern="[A-Za-z]{3,}"
title="3+ letters, no numbers"
oninvalid="this.setCustomValidity('Please enter valid username')"
oninput="this.setCustomValidity('')">