I am working on a JSF page which has a dropdown based on List<SelectItem>:
<h:selectOneMenu value="#{bean.selectedItem}">
<f:selectItems value="#{bean.availableItems}" />
</h:selectOneMenu>
I need to get both the value and label of the currently selected item. Right now I only get the value. How can I get the label, too?
You can’t. That’s just how HTML works. You know, JSF is a HTML code generator. The JSF
<h:selectOneMenu>generates a HTML<select><option>. The HTML<select>element will only send thevalueattribute of the selected<option>element. It will not send its label.But that shouldn’t be a big issue. You namely already know both the value and label in the server side, inside the
#{bean.availableItems}. All you need to do to get the associated label is to get it by the value as key. I suggest to make it aMapwhich in turn can also be used inf:selectItems.Basic kickoff example:
with
and in result
An alternative is to wrap both name and value in a javabean object representing an entity and set the whole object as value, via a converter.
See also:
selectOneMenuwiki page