HTML Forms
HTML forms are essential for collecting user input on web pages. They allow users to enter information such as text, email, passwords, and more. In this guide, we will explore the key elements of HTML forms: <form>
, <input>
, <label>
, <textarea>
, and <button>
.
1. The <form>
Element
The <form>
element is the container for all form-related elements. It defines how data should be sent and processed.
Example:
<form action="submit.php" method="post">
<label for="name">Name:</label>
<input type="text" id="name" name="name">
<button type="submit">Submit</button>
</form>
<form>
Attributes:
Attribute | Description | Example Value |
---|---|---|
action | URL where form data is sent | "submit.php" |
method | HTTP method (GET or POST ) |
"post" |
enctype | Encoding type for form data | "multipart/form-data" |
autocomplete | Enables autocomplete | "on" |
novalidate | Disables validation | novalidate |
2. The <input>
Element
The <input>
element is used to create form fields.
Example:
<input type="email" name="email" placeholder="Enter your email">
Common <input>
Attributes:
Attribute | Description | Example Value |
---|---|---|
type | Defines the input type | "text" , "email" , "password" |
name | Specifies the input name | "username" |
placeholder | Displays hint text | "Enter your name" |
required | Makes input mandatory | required |
value | Defines default value | "John Doe" |
3. The <label>
Element
The <label>
element provides a clickable text for form fields, improving accessibility.
Example:
<label for="email">Email:</label>
<input type="email" id="email" name="email">
<label>
Attributes:
Attribute | Description | Example Value |
---|---|---|
for | Links label to an input field by ID | "email" |
4. The <textarea>
Element
The <textarea>
element is used for multiline text input.
Example:
<textarea name="message" rows="4" cols="50" placeholder="Type your message..."></textarea>
<textarea>
Attributes:
Attribute | Description | Example Value |
---|---|---|
name | Identifies the field name | "message" |
rows | Defines number of visible rows | "4" |
cols | Defines width in characters | "50" |
placeholder | Displays hint text | "Enter your message" |
5. The <button>
Element
The <button>
element allows users to submit forms or perform other actions.
Example:
<button type="submit">Send</button>
<button>
Attributes:
Attribute | Description | Example Value |
---|---|---|
type | Specifies button type | "submit" , "reset" , "button" |
disabled | Disables the button | disabled |
Conclusion
HTML forms are fundamental in web development, allowing users to input data efficiently. By using the right elements and attributes, you can create accessible and user-friendly forms.