How to conditionally render an f:selectItem tag?

Viewed 39285

How can I specify a conditional rendering for an <f:selectItem> tag. I need to display <f:selectItem> options according to a specific user's status.

For example, I wanted something like:

<f:selectItem itemLabel="Yes! I need a girlfriend!"
             rendered="false(or some boolean condition)"
             itemValue="o1"/>
8 Answers

For me the "cleanest" way is in 2019 using JSF 2.3 and in order to avoid mixing jsf/html with jstl to

  1. set itemDisabled="true" and
  2. a custom class using jsf/passthrough pt:class="hidden".
<f:selectItem itemValue="itsValue" itemLabel="example"
    itemDisabled="#{exampleBean.hideItem}" 
    pt:class="#{exampleBean.hideItem ? 'hidden' : ''}" />

Of cause you need then the CSS style

.hidden {
    display: none !important;
}

This has the advantage that there can be still disabled elements in your list.

You can also hide it using JS (jQuery). On Primefaces:

$('.ui-selectoneradio .ui-state-disabled').closest('tr').hide();

This is for p:selectOneRadio. Note that if you update the component or a container of the component, you must re-run the code.

Related