Set Focus To Inputtext On Validation Error
I want to set focus on inputText field in JSF when there is a validation error on that particular inputText. How can I implement this? I thought validatorMessage on the inputText w
Solution 1:
There is no such default behaviour. You need to implement it yourself or use a 3rd party library for the job. Basically, during the render response you need to walk through the submitted form for all UIInput
components and find the first one whose isValid()
returns false
and then store its client ID in the request map so that you can print it as a JS variable.
form.visitTree(VisitContext.createVisitContext(), newVisitCallback() {
@Overridepublic VisitResult visit(VisitContext context, UIComponent component) {
if (component instanceof UIInput && !((UIInput) component).isValid()) {
context.getFacesContext().getExternalContext().getRequestMap()
.put("focus", component.getClientId(context.getFacesContext()));
return VisitResult.COMPLETE;
}
return VisitResult.ACCEPT;
}
});
Then you can use the following script to set the focus:
<h:outputScripttarget="body">
var focus = '#{focus}';
if (focus) {
document.getElementById(focus).focus();
}
</h:outputScript>
The JSF utility library OmniFaces has a reuseable component for this, the <o:highlight>
(source code here and showcase demo here). It additionally also sets a styleclass on the invalidated inputs so that you can specify for example a different background color by CSS.
Post a Comment for "Set Focus To Inputtext On Validation Error"