change selected item text from primefaces selectonemenu

3.4k views Asked by At

enter image description here

The label of the selectItem is combined by the item value and a description text. If i select a item the whole itemLabel will be displayed in the textbox. I would like to change that, the textbox should only display the itemValue of the selectedItem and not the Label. So instead of "0 - Variante #0" only "0".

How i fill the menu:

<p:selectOneMenu id="z2Menu" value="#{createCarProject.z2}">                     
   <f:selectItem itemLabel="" itemValue="" />
   <f:selectItems value="#{createCarProject.z_list}" var="i" itemLabel="#{i.value} - #{i.label}" itemValue="#{i.value}"/>
</p:selectOneMenu>

.

2

There are 2 answers

1
Miguel On BEST ANSWER

I think the only way is changing the CSS style with JS. I put an example:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
    xmlns:ui="http://java.sun.com/jsf/facelets"
    xmlns:h="http://java.sun.com/jsf/html"
    xmlns:f="http://java.sun.com/jsf/core"
    xmlns:p="http://primefaces.org/ui">

<h:head>
    <script>
        function changeLabel(select) {
            if (select.value != '')
                $(".ui-selectonemenu-label").text(select.value);
        }
    </script>
</h:head>

<h:body>
    <h:form id="form">
        <p:selectOneMenu id="console" value="#{dumpController.message}"
            style="width:125px" onchange="changeLabel(this)">
            <f:selectItem itemLabel="Select One" itemValue="" />
            <f:selectItem itemLabel="Xbox One" itemValue="1" />
            <f:selectItem itemLabel="PS4" itemValue="2" />
            <f:selectItem itemLabel="Wii U" itemValue="3" />
        </p:selectOneMenu>
    </h:form>
</h:body>
</html>
1
BalusC On

You can achieve this with <p:selectOneMenu var>.

<p:selectOneMenu ... var="item">
    <f:selectItems value="#{bean.items}" var="item" itemLabel="#{item.value}" />
    <p:column>#{item.value} - #{item.label}</p:column>
</p:selectOneMenu>

The itemLabel is what will be shown in the "textbox" as you call it and the <p:column> is what will be shown in the menu. No need for JS based workarounds here. If you're not in PrimeFaces 5+ yet, then you need an additional layout="custom" attribute on <p:selectOneMenu>.

It has only a bit different style (borders and such), but that can easily be taken care of with help of a shot of CSS.