Tuesday, November 15, 2016

Quick Solution: change selectOneMenu List based on inputText value

You need a <f:ajax listener> inside inputText. The inputChanged method will be called after value changed in inpuText field and update the list of selectOneMenu.

Here id of selectOneMenu is result. And that is mentioned in render attribute of <f:ajax listener>.

The JSF page: index.xhtml

<?xml version='1.0' encoding='UTF-8' ?>
<!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:h="http://java.sun.com/jsf/html"
      xmlns:f="http://java.sun.com/jsf/core">
    <h:head>
        <title>Test</title>
    </h:head>
    <h:body>
        <h:form>
            <h:inputText value="#{valueTest.input}">
           
                <f:ajax listener="#{valueTest.inputChanged}" render="result"/>
            </h:inputText>

          
            <h:selectOneMenu id="result">
                <f:selectItems value="#{valueTest.lst}" />
            </h:selectOneMenu>
        </h:form>
       
       
    </h:body>
</html>
 

Managed Bean: ValueTest.java

@ManagedBean
@RequestScoped
public class ValueTest {

    /**
     * Creates a new instance of ValueTest
     */
    public ValueTest() {
    }
   
    @PostConstruct
    private void init()
    {
        lst = new ArrayList();
    }
           
    private String input;
   
    private List lst;

    private String result;
    public String getInput() {
        return input;
    }

    public void setInput(String input) {
        this.input = input;
    }

    public String getResult() {
        return result;
    }

    public void setResult(String result) {
        this.result = result;
    }
   
   
    public void inputChanged(AjaxBehaviorEvent e)
    {
        result = input;
        lst.clear();
        if(result.equals("01"))
        {
            lst.add("01");
            lst.add("02");
        }
        else if(result.equals("05"))
        {
            lst.add("05");
            lst.add("06");
        }
    }


    public List getLst() {
        return lst;
    }

    public void setLst(List lst) {
        this.lst = lst;
    }
   
}
 

No comments:

Post a Comment