A thing that I have strived for as long as I can remember is simplicity and ease of use in the work that I do. When working with HTML forms a key manifestation of this philosophy is something as simple as being able to click a label and have focus to be set to the corresponding form-field, i.e. input
; textarea
; or select
element. When I first started doing this, my approach was to use the for
attribute of the label
element, so that its value matched the id
of the form-field, e.g.:
<label for="inputId">Label</label> <input id="inputId" type="" />
While the above model works from a usability standpoint it fails (in my opinion) from a maintainability standpoint, as you need to either manually or programmatically ensure that the for
attribute in the label
element matches the id
attribute of the corresponding form-field.
… but there’s a better way: If you nest the form-field inside of the label
, clicking any part of the element or its descendants will set focus to the form-field without requiring any additional attributes whatsoever. The structure for this is:
<label>Label </label>
… e.g.:
<label>Input <input type="" /></label> <label>Textarea <textarea></textarea></label> <label>Select <select></select></label>
From here on it’s really up to you to structure your form-control (i.e. combination of label
and form-field) in any way you want. My current model is inspired by the naming conventions of the BEM (Block, Element, Modifier) methodology and looks like, e.g.:
<label class="formcontrol"> <span class="formcontrol-label">Label</span> <input class="formcontrol-input" type="text" /> <label>
Note #1: You can (of course) use any inline element for stying. It doesn’t have to be a <span>
.