HTML forms are used to collect user inputs on a website. They are created using the <form> element, which acts as a container for other form elements like <input>, <label></label>, and <button></button>.
In this lesson, you'll learn how to create a simple contact form using these elements. The final code will be a contact form that includes fields for the user's name, email, and a message. Let's get started!
First, let's create the form container using the <form> element. Add the following code:
<form></form>
<form> element isn't visible. The input fields that we will put inside it are.
In this step, we will add input fields for the user's name and email. Input fields are used to collect information from the user. The type attribute specifies the type of input, such as text or email, and the id attribute is used to identify the input when the form is submitted. The placeholder attribute provides a hint to the user about what they should enter in the input field.
Inside the <form> element, add the following code:
<form>
<input type="text" id="txtName" placeholder="Your name"><br>
<input type="email" id="txtEmail" placeholder="Your email">
</form>
Here is a list of some common input types:
| Type | Description |
|---|---|
| text | Used for single-line text input |
| Used for email addresses | |
| password | Used for password input, hides the characters |
| number | Used for numeric input |
| date | Used for date input |
| checkbox | Used for checkboxes, allows multiple selections |
| radio | Used for radio buttons, allows single selection |
Labels are important for accessibility and usability. They describe the purpose of the input fields and make it easier for users to understand what information is required. The <label> element is used to associate a text label with a specific form control, such as an input field, by using the for attribute. The value of the for attribute should match the id attribute of the associated form control.
Add the following code inside the <form> element, before each input field:
<form>
<label for="txtName">Name:</label><br>
<input type="text" id="txtName" placeholder="Your name"><br>
<label for="txtEmail">Email:</label><br>
<input type="email" id="txtEmail" placeholder="Your email">
</form>
In this step, we will add a textarea element to our form. A textarea is a multi-line text input field that allows users to enter larger amounts of text, such as a message or a comment. The rows attribute specifies the number of visible text lines, and the cols attribute specifies the number of visible text columns.
Now, let's add a textarea for users to enter their message. Add the following code inside the <form> element, after the email input field:
<label for="txtMessage">Message:</label><br><textarea id="txtMessage" rows="4" cols="50"></textarea>