HTML forms are used to collect user input and send it to a server for processing. Forms are essential for creating interactive and dynamic web applications.
A form is created using the <form> element. Inside the form, various form elements can be used to collect different types of input from the user.
HTML provides several input types to capture different kinds of user data. Here are some of the most common input types:
Input Type | Description | Example |
---|---|---|
text | Allows the user to enter a single-line text input. |
Try yourself
|
password | Allows the user to enter a password, where the characters are masked. |
Try yourself
|
Allows the user to enter an email address. |
Try yourself
|
|
number | Allows the user to enter a number. |
Try yourself
|
checkbox | Allows the user to select one or more options. |
Try yourself
|
radio | Allows the user to select one option from a group. |
Try yourself
|
submit | Creates a button to submit the form data to a server. |
Try yourself
|
reset | Creates a button to reset the form data to its initial values. |
Try yourself
|
The <textarea> element is used to create a multi-line text input field.
<textarea name="message" rows="4" cols="50" placeholder="Enter your message"></textarea>
The <select> element is used to create a drop-down list.
<select name="cars">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
The <button> element is used to create a clickable button.
<button type="button">Click Me!</button>
Here is a complete example of an HTML form with various input types:
<form action="/submit_form" method="post">
<label for="username">Username:</label>
<input type="text" id="username" name="username" required>
<br>
<label for="password">Password:</label>
<input type="password" id="password" name="password" required>
<br>
<label for="email">Email:</label>
<input type="email" id="email" name="email" required>
<br>
<label for="age">Age:</label>
<input type="number" id="age" name="age" min="1" max="100" required>
<br>
<label for="gender">Gender:</label>
<input type="radio" id="male" name="gender" value="male">
<label for="male">Male</label>
<input type="radio" id="female" name="gender" value="female">
<label for="female">Female</label>
<br>
<label for="message">Message:</label>
<textarea id="message" name="message" rows="4" cols="50"></textarea>
<br>
<label for="cars">Choose a car:</label>
<select id="cars" name="cars">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
<br>
<input type="checkbox" id="subscribe" name="subscribe" value="newsletter">
<label for="subscribe">Subscribe to newsletter</label>
<br>
<input type="submit" value="Submit">
<input type="reset" value="Reset">
</form>
Here are some important notes and best practices when creating forms in HTML: