Tag Archives: Usability

Auto-focusing HTML form-fields with smart labels

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>


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">
    <b class="formcontrol-label">Label</b>
    <input class="formcontrol-input" type="text" />

Note #1: I don’t use elements for styling (anymore), so the <b> element is really just an inline-element which takes up less characters than, e.g. a <span>.