(Progress persistence is disabled until Phase 9)
Input Elements
Learn how to collect various types of text and numeric data from users.
Learning Objectives
- Learn to use the input tag
- Understand different input types like text, password, and email
- Learn how to use labels to improve accessibility
The Input Element
The most common way to collect user data is the <input> tag.
Like the <img> tag, <input> is an empty element (it has no closing tag). The magic of the <input> tag comes from its type attribute, which completely changes how the input behaves!
Text Input
The default type is text. This creates a standard, single-line text box.
<input type="text" placeholder="Enter your username">
(The placeholder attribute adds temporary, gray text inside the box to give the user a hint).
Password Input
If you are collecting sensitive information, use type="password". This looks like a text input, but it hides the characters the user types (replacing them with dots or asterisks).
<input type="password" placeholder="Enter your password">
Email Input
Using type="email" tells the browser that this field specifically expects an email address. On mobile phones, this automatically changes the user’s keyboard to show the @ symbol!
<input type="email" placeholder="you@example.com">
The Label Element
A text input by itself is not very useful if the user doesn’t know what they are supposed to type. We should always provide a label.
The <label> tag defines a label for an input element. It is crucial for accessibility.
To connect a <label> to a specific <input>, you use the for attribute on the label, and give the input a matching id attribute.
Code Example
<form>
<label for="username">Username:</label>
<input type="text" id="username" name="user_name">
<label for="pwd">Password:</label>
<input type="password" id="pwd" name="user_password">
</form>
When you properly link a <label> to an <input> using for and id, clicking on the text of the label automatically focuses the cursor inside the input box!
The Name Attribute
Notice the name attribute in the example above. While the id connects the input to the label, the name attribute is what the server uses to identify the data when the form is submitted. Without a name, the input’s data will not be sent!
Try It Yourself
Try building a simple login form with a username and password field!
Key Takeaways
- The
<input>tag is used to collect user data and has no closing tag. - The
typeattribute changes the input’s behavior (text,password,email). - Use the
<label>tag with aforattribute that matches the input’sidfor accessibility. - The
nameattribute is required to actually send the data to a server.