Are there reasons to prefer using the HTML5 element "label"
- to wrap the "input" element
- with a "for" attribute
i.e. to prefer
<label><input></label>
to
<label for="inp"></label><input id="inp">
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.