0

Are there reasons to prefer using the HTML5 element "label"

  1. to wrap the "input" element
  2. with a "for" attribute

i.e. to prefer

<label><input></label>

to

<label for="inp"></label><input id="inp">
fadedbee
  • 42,671
  • 44
  • 178
  • 308

1 Answers1

0

Yes there is a reason for this.

The element does not render as anything special for the user. However, it provides a usability improvement for mouse users, because if the user clicks on the text within the element, it toggles the control.

when you include <label for="#yourControlID"><input id="yourControlID"></label> it will attach with that particular input control. For example look at the below snippet.

<form action="demo_form.asp">
  <label>Male</label>
  <input type="radio" name="sex" id="male" value="male"><br>
  <label for="female">Female</label>
  <input type="radio" name="sex" id="female" value="female"><br>
  <input type="submit" value="Submit">
</form>

Try clicking on label - Male. The toggle doesn't happen but if you click on label-female it toggles.

So basically what it does is, when you try to remove for from label it will stop binding that particular label to the control and when you click on the label without for in it, it will not actually toggle the radio element.

SOURCE

Guruprasad J Rao
  • 29,410
  • 14
  • 101
  • 200
  • Thanks for your answer, but my question was about choosing the best way to link a label to an input. One option is to nest the `` inside. Another is to have the elements as peers and use the `for` and `id` attributes. Which is best? – fadedbee Mar 30 '15 at 15:45
  • 2
    I think **[this liink](http://stackoverflow.com/questions/774054/should-i-put-input-tag-inside-label-tag)** will give you more clear answer. Hope it helps.. :) – Guruprasad J Rao Mar 30 '15 at 15:54
  • Thanks I just found that too and have already voted to close my question as a duplicate. – fadedbee Mar 30 '15 at 16:05
  • Oh.. Its ok.. Happy coding.. :) – Guruprasad J Rao Mar 30 '15 at 16:08