Purpose of the h:outputLabel and its “for” attribute

It’s easier to understand if you learn basic HTML first. JSF is in the context of this question namely merely a HTML code generator. There’s an excellent HTML tutorial at htmldog.com. The <label>, as generated by <h:outputLabel>, is explained here.

HTML Tag: label

Label for a form element (input, textarea or select).

Optional Attributes

for can be used to associate the label to a form element when the value of for matches the value of an element’s id attribute.

Example

<label for="email">Email address</label>
<input type="text" name="email" id="email" />

So the for attribute must point to the id of the input component the label is intented to label. The label has the following SEO and usability advantages:

  1. It tells in text about the associated input element.
  2. It focuses and activates the associated input element when being focused/clicked itself.

As JSF is in the context of this question merely a HTML code generator, exactly the same applies to JSF components generating that HTML as well.

<h:outputLabel for="email">Email address</h:outputLabel>
<h:inputText id="email" />

Searchbots will find the label and index the associated input element as such. Screenreaders as used by visually disabled people will find the label and tell its contents by sound. Endusers can click the label to see the associated input getting focused. Checkboxes/radiobuttons will be selected when clicking the label. File inputs will open the browse dialog when clicking the label. Etcetera.


Noted should be that relatively a lot of low-quality JSF tutorials are abusing the <h:outputLabel> with the sole purpose to print out some Hello World text like so:

<h:outputLabel value="#{bean.message}" />

This particular use case is thus wrong. Instead, a <h:outputText> should have been used:

<h:outputText value="#{bean.message}" />

Or even just EL in template text:

#{bean.message}

If you ever encounter such a tutorial who’s abusing the <h:outputLabel> this way, it’s strongly recommended to stop reading it and head to a more self-respected resource. This is a strong indication that the tutorial’s author know nothing about basic HTML while that’s in turn a pretty important prerequisite before learning JSF. One who barely know anything about basic HTML surely isn’t a good JSF teacher. You never know if such a low-quality learning resource continues into a downward spiral of teaching bad practices and it’s therefore better to head to a different one. You can find sane resources linked at bottom of our JSF wiki page and at jsf.zeef.com.

Leave a Comment