Search code examples
primefacesattributesfocusexplicit

How can I obtain explicit focus via the 'for' attribute on p:focus?


According to the documentation, it should be possible to explicitly declare that a form input element component receives focus via the 'for' attribute. In this case, the second visible and enabled input element rather than the first by default - so can someone please help me by explaining why the following doesn't work?

<h:form id="form4">
   <p:focus id="pick" for="input2" />   
   <h:inputText id="input1" value="#{messageManagedBean.message1}"/>
   <h:inputText id="input2" value="#{messageManagedBean.message2}"/>

   <p:commandButton value="Execute JSF Lifecycle - Invoke Action One" action="#{messageManagedBean.doSomeAction41}" ></p:commandButton>
   <p:commandButton value="Execute JSF Lifecycle - Invoke Action Two" 
action="#{messageManagedBean.doSomeAction42}" ></p:commandButton>   

   <p:messages for="input1" id="messages1" autoUpdate="true"/>
   <p:messages for="input2" id="messages2" autoUpdate="true"/>

</h:form>

Many thanks!

[PrimeFaces: 3.5.25 JavaServer Faces: 1.2 Java Servlet: 2.5 Server: Apache Tomcat 8.0.15]


Solution

  • If you check the source of the p:focus renderer, you will see (in case you set for) the component is resolved and a bit of JavaScript is written:

    writer.write("$(function(){");
    writer.write("PrimeFaces.focus('" + clientId +"');");
    writer.write("});");
    

    Since it's not working for your software stack, you could omit p:focus and simply write the JavaScript yourself:

    <h:form id="form4">
       <script>
           $(function(){ PrimeFaces.focus('form4:input2'); });
       </script>
       <h:inputText id="input1" value="#{messageManagedBean.message1}"/>
       <h:inputText id="input2" value="#{messageManagedBean.message2}"/>
       ...
    </h:form>
    

    Yes, this is a hack. If you can, upgrade your software stack. For me your XHTML is working.