Home > Enterprise >  Why do we use "for" attribute inside label tag?
Why do we use "for" attribute inside label tag?

Time:02-11

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?

CodePudding user response:

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.

CodePudding user response:

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 this case, you can skip it and it will be fine.

  • Related