Why do we use "for" attribute inside label tag?

Viewed 63

I've been learning about the "for" attribute in HTML and what it does but I've stumbled upon a weird example that I've yet to understand

Code1

<input id="indoor" type="radio" name="indoor-outdoor">
<label for="indoor">Indoor</label>

Code2

<label for="loving"><input id="loving" type="checkbox" name="personality"> Loving</label>
<br>
<label><input type="checkbox" name="personality"> Loving</label>

I understand why "for" is used in the first block of code but I don't understand why the second code used "for" and "id" implicitly when it could've just worked fine without them. Any help?

3 Answers

It is correct, that it works without it. But it is useful to connect the label with the input field. That is also important for the accessibility (e.g. for blind people, the text is read).

The browsers also allow you to click the labels and automatically focus the input fields.

For checkboxes this can be useful as well. But for these, you could also surround the checkbox-input like this:

<label>
  <input type="checkbox"> I agree with the answer above.
</label>

In this case, the checkbox is automatically checked when you click on the text.

The surrounding of the inputs with a label works with every input field. But the text, that describes the input field, should always be inside it. That what for is for: When your HTML disallows the label-surrounding, you can use the for-attribute.

The the both following examples:

Simple stuctured:

<label>
  Your Name:<br>
  <input type="text"/>
</label>

Complex structure around input fields:

<div class="row">
  <div class="col">
    <label for="name">Your Name:</label>
  </div>
  <div class="col">
    <input type="text" id="name" />
  </div>
</div>

To be able to use the label with the check box. E.g., when rendered, click the label and it will toggle the check box ticked state.

Edit: Further to this, it allows putting the label anywhere on the page.

It could be used without "for" attribute, and it will be fine, according to docs. This is just one option how to use "for" to omit confusing developers. Anyway, in case of placing checkbox inside label, you can skip "for" and it will be fine.

<!-- labelable form-relation still works -->
<label><input type="checkbox" name="personality"> Loving</label>

"for" approach much preferable if you want to style it, f.e. using Bootstrap

<div class="form-check">
  <input class="form-check-input" type="checkbox" value="" id="flexCheckDefault">
  <label class="form-check-label" for="flexCheckDefault">
    Default checkbox
  </label>
</div>
Related