JSF Select Menu Auto Submit on Value Change

When you have a form with only one field, do you really need a submit button? You assume the user will want to submit once they fill out that field, right? Let’s get rid of it and make our application that much simpler.

In this instance, our single field is a select menu and we want to automatically submit the form when the drop-down menu changes.

This solution was built using JSF 2.0 and Java:

1. Add a submit and valueChangeListener to your selectOneMenu tag:

onchange="submit()" valueChangeListener="#{itemBean.retrieveStatusInfo}"

ORIGINAL STATE: Button for submit after menu change

<h:outputText value="Select Item"/> <h:selectOneMenu value="#{itemBean.currentItem}">   <f:selectItems value="#{itemBean.items}" var="item" itemValue="#{item.name}" itemLabel="#{item.name}"/> </h:selectOneMenu> <br/>
<p:commandButton value="Get Status" update=":mainForm" actionListener="#{itemBean.retrieveStatusInfo}"/>

NEW STATE: Auto submit on change

<h:selectOneMenu value="#{itemBean.currentItem}" onchange="submit()" valueChangeListener="#{itemBean.retrieveStatusInfo}"> 
  <f:selectItems value="#{itemBean.items}" var="item" itemValue="#{item.name}" itemLabel="#{item.name}"/>

2. Notice we remove the commandButton from the jsf code as it is no longer necessary.

3. Update the retrieveStatusInfo() method in the ItemBean.java class to get the value from the drop-down:

  public void retrieveStatusInfo(ValueChangeEvent e) {     currentItem = e.getNewValue().toString();     if(currentItem != null) {       clientService.getStatusInfoForItem(currentItem);     }   }