Focus component helps you manage focus of input components in the view.
The component can be used either in a form or in a view - there can be only one focus per form and, if both, form- and view-based focuses are defined, a form one takes a priority. A view-based focus defines behavior for all forms in a view.
Focus reflects results of validation of components in a view. Focus is given to a first input component in a page which is invalid. The order of input components is determined on client-side and it reflects tabindex and position in a page. You can prioritize focusing of specific component by increasing its tabindex.
Focus can be configured to keep focus on input component which has been focused before form submission.
Focus is applied each time it is rendered - either on form submission or after AJAX request. To turn off focusing after AJAX request, you can use ajaxRendered=false.
In following example, focus is initially given to Name input. If you enter invalid name (less than 3 chars) and submit (hit enter), focus is given again to Name input. This way user is directed to enter valid input.
<!DOCTYPE html> <ui:composition xmlns="http://www.w3.org/1999/xhtml" xmlns:h="http://java.sun.com/jsf/html" xmlns:f="http://java.sun.com/jsf/core" xmlns:ui="http://java.sun.com/jsf/facelets" xmlns:a4j="http://richfaces.org/a4j" xmlns:rich="http://richfaces.org/rich"> <rich:panel header="Focus and Form Input Validation"> <h:form id="form"> <rich:focus /> <h:panelGrid columns="3" id="grid"> <h:outputText value="Name:" /> <h:inputText label="Name" id="name" value="#{userBean.name}"> <f:validateRequired /> <f:validateLength minimum="3" /> </h:inputText> <rich:message for="name" ajaxRendered="true" /> <h:outputText value="Job:" /> <h:inputText label="Job" id="job" value="#{userBean.job}"> <f:validateRequired /> <f:validateLength minimum="3" maximum="50" /> </h:inputText> <rich:message for="job" ajaxRendered="true" /> <h:outputText value="Address:" /> <h:inputText label="Address" id="address" value="#{userBean.address}"> <f:validateRequired /> <f:validateLength minimum="10" /> </h:inputText> <rich:message for="address" ajaxRendered="true" /> <h:outputText value="Zip:" /> <h:inputText label="Zip" id="zip" value="#{userBean.zip}"> <f:validateRequired /> <f:validateLength minimum="4" maximum="9" /> </h:inputText> <rich:message for="zip" ajaxRendered="true" /> </h:panelGrid> <a4j:commandButton value="Ajax Validate" oncomplete="highlightInvalidInputs()"/> </h:form> </rich:panel> <h:outputScript> highlightInvalidInputs = function() { var rows = $(#{rich:element('grid')}).find('tr'); rows.find('input').removeClass('invalid'); rows.has('.rf-msg-err').find('input').addClass('invalid') } </h:outputScript> <style> .invalid { border-color: #D91C0D !important; } </style> </ui:composition>