1

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?

aynber
  • 22,380
  • 8
  • 50
  • 63
Antares42
  • 1,406
  • 1
  • 15
  • 45

1 Answers1

0

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.

Antares42
  • 1,406
  • 1
  • 15
  • 45
  • One alternative similar to what is discussed by BalusC in [this question](http://stackoverflow.com/questions/14238646/how-to-escape-fselectitem-itemlabel-attribute) would be to use ``itemEscaped="false"`` and inject the English labels as comments like so: ``Localized_Label``, but that appears to work only for ``SelectOneRadio`` and not for ``SelectOneMenu`` or ``SelectManyMenu``, where all tags are cleaned away automatically. – Antares42 Jul 09 '13 at 09:25