Set focus to inputText on validation error

孤人 提交于 2020-01-06 02:36:05

问题


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 would do this out of the box but it appears not.


回答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(), new VisitCallback() {

    @Override
    public 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:outputScript target="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.



来源:https://stackoverflow.com/questions/11205604/set-focus-to-inputtext-on-validation-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!