The JSF-2 tag f:selectItems that iterates over a collection of POJOs offers the parameters value
and itemLabel
These generate <option>
elements of the form
<option value="value">itemLabel</option>
Now, HTML offers another attribute called label
for the <option>
tag
<option value="value" label="something_else">itemLabel</option>
but I can't see any way how to make use of that one through JSF. The background for the question is that I have my itemLabels in a localized language, but want Select2 (which replaces the <select>
here) to be able to autocomplete and match the English name, too. This I want to hide in the label
attribute.
Any ideas?
I solved this by what I consider a rather dirty trick:
I generated the options using f:selectItems
as follows:
<h:selectManyMenu class="MySelectField" id="MySelectField" name="input"
value="#{...}" converter="...">
<f:selectItems value="#{...}" var="..."
itemLabel="Localized_Label|EnglishLabel/NorwegianLabel"
/>
</h:selectManyMenu>
producing
<option value="SOME_CODE">Localized_Label|EnglishLabel/NorwegianLabel</option>
I then jQueried the part I want to hide into the label
attribute (and configured Select2 to also match user input against said attribute):
$(document).ready(function() {
$(".MySelectField option").each(function(){
tmp=$(this).text().split("|");
$(this).attr('label',tmp[1]);
$(this).text(tmp[0]);
});
$(".MySelectField").select2({
matcher: function(term, text, opt) {
return text.toUpperCase().indexOf(term.toUpperCase())>=0
|| opt.attr("label").toUpperCase().indexOf(term.toUpperCase())>=0;
}
});
});
resulting in
<option value="SOME_CODE" label="EnglishLabel/NorwegianLabel">Localized_Label</option>
with a Select2 called on top of that.
This now allows the user to get Select2's autocompletion both for English and Norwegian input, irrespective of the chosen localization.