0

I have a task to pre-select some entry from the <select> element, based on the current element of the collection that I'm iterating through.

We are using JSF to render html, and there is a loop that iterates through some collection. Based on the current item during iteration, I have to add or not add selected attribute to the <option> tag.

The problem is that selected doesn't take any value, it just have to be present in the tag so that the item is pre-selected in the <select> tag. I tried with selected=true/false but it didn't work. So this is what I tried and JSF returns parse exception:

<select value="#{...}">
    <c:forEach items="#{registrationManagementBean.offersMap}" var="entry" rowIndexVar="rowIndex">
        <option #{registrationManagementBean.offerId == entry.key? 'selected' : ''} value="#{entry.key}">#{entry.value}</option>
    </c:forEach>
</select>

and that produces:

Error Traced[line: 213] Element type "option" must be followed by either attribute specifications, ">" or "/>".

When I try selected = #{registrationManagementBean.offerId == entry.key? 'true' : 'false'}, that renderes correctly, but it is not functional.

Is there a way to implement this need?

Jasper de Vries
  • 19,370
  • 6
  • 64
  • 102
wdc
  • 2,623
  • 1
  • 28
  • 41

1 Answers1

2

The following is invalid in XML, and that is causing the error you're seeing:

<option selected>Value</option>

It should be:

<option selected="selected">Value</option>

That being said, it is strange to be rendering your own select elements when you are using JSF. Use JSF the way it is supposed to be used, and use a h:selectOneMenu to render a select element. With a JSF component, stuff like value binding and validation are easily configurable options.

See also:

Jasper de Vries
  • 19,370
  • 6
  • 64
  • 102