Problem Statement
How do you associate a label with an input field?
Explanation
You associate a label with an input field by using the for attribute on the label that matches the id attribute on the input. For example, label for equals username matches input id equals username. This creates an explicit association between the label and input. When properly associated, clicking the label focuses the input field, making forms easier to use. This is especially helpful for small checkboxes and radio buttons. The association is also crucial for accessibility. Screen readers announce the label text when users focus on the input, helping visually impaired users understand what to enter. You can also implicitly associate labels by wrapping the input inside the label tag, but explicit association with for and id is preferred for clarity and flexibility. Using labels correctly is a fundamental best practice for accessible forms.
Code Solution
SolutionRead Only
<!-- Explicit association (recommended) -->
<form>
<label for="username">Username:</label>
<input type="text" id="username" name="username">
<label for="email">Email:</label>
<input type="email" id="email" name="email">
</form>
<!-- Implicit association -->
<form>
<label>
Username:
<input type="text" name="username">
</label>
</form>
<!-- Labels with checkboxes -->
<form>
<label for="terms">
<input type="checkbox" id="terms" name="terms" required>
I agree to the terms and conditions
</label>
</form>
<!-- Complete form with labels -->
<form action="/submit" method="POST">
<div>
<label for="fname">First Name:</label>
<input type="text" id="fname" name="firstname" required>
</div>
<div>
<label for="lname">Last Name:</label>
<input type="text" id="lname" name="lastname" required>
</div>
<button type="submit">Submit</button>
</form>