The form
tag defines an HTML form used to collect input from users. It can include fields like text inputs, radio buttons, checkboxes, dropdowns, submit buttons, and more.
When the form is submitted, the data can be sent to a server or handled via JavaScript.
✅ Basic Syntax
<form action="/submit" method="post">
<label for="name">Name:</label>
<input type="text" id="name" name="username">
<input type="submit" value="Send">
</form>
⚙️ Key Attributes
Attribute | Description |
---|---|
action | URL where the form data is sent (e.g., /submit , form-handler.php ) |
method | HTTP method: GET (default) or POST |
target | Where to open the response (e.g., _blank , _self ) |
enctype | Encoding type (important for file uploads, e.g., multipart/form-data ) |
autocomplete | Enables or disables browser autocomplete (on or off ) |
🎯 Common Form Elements
Tag | Purpose |
---|---|
<input> | General input field (text, email, etc.) |
<textarea> | Multi-line text input |
<select> | Dropdown menu |
<option> | Option inside <select> |
<label> | Label for a form element |
<button> | Clickable button |
<fieldset> | Groups related form elements |
<legend> | Title for a <fieldset> |
🧩 Example with Multiple Inputs
<form action="/register" method="post">
<label for="email">Email:</label>
<input type="email" id="email" name="user_email" required>
<label for="password">Password:</label>
<input type="password" id="password" name="user_password" required>
<label>
<input type="checkbox" name="subscribe"> Subscribe to newsletter
</label>
<input type="submit" value="Register">
</form>
🛠️ Styling Forms (CSS Example)
form {
max-width: 400px;
margin: 20px auto;
}
input[type="text"],
input[type="email"],
input[type="password"] {
display: block;
width: 100%;
padding: 10px;
margin-bottom: 10px;
}
🚀 Form Handling
- With backend: Send data to server via
action="/process.php"
or similar - With JavaScript: Use
onsubmit
oraddEventListener('submit', ...)
to handle it client-side
✅ Summary
Feature | <form> Tag |
---|---|
Purpose | Collect and submit user input |
Contains | Input fields, buttons, and more |
Works with | Backend languages, or client-side JS |
Modern Use | Combined with validation, AJAX, APIs |