在验证错误时将焦点设置为inputText [英] Set focus to inputText on validation error

查看:191
本文介绍了在验证错误时将焦点设置为inputText的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果在特定的inputText上存在验证错误,我想在JSF中将焦点设置在inputText字段上。我怎么能实现这一点?



我认为inputText上的validatorMessage可以做到这一点,但它似乎不是。

解决方案

没有这样的默认行为。您需要自己实施或使用第三方库来完成这项工作。基本上,在呈现响应期间,您需要遍历提交的表单,以查看所有 UIInput 组件,找到第一个 isValid() 返回 false ,然后将其客户端ID存储在请求映射表中,以便将其打印为JS变量。 > form.visitTree(VisitContext.createVisitContext(),new VisitCallback(){
$ b @Override
public VisitResult visit(VisitContext context,UIComponent component){$ b (b)if(UIInput&!((UIInput)component).isValid()){
context.getFacesContext()。getExternalContext()。getRequestMap()
.put(focus ,component.getClientId(context.getFacesConte XT()));
返回VisitResult.COMPLETE;
}

返回VisitResult.ACCEPT;
}
});

然后您可以使用以下脚本来设置焦点:$ b​​
$ b

 < h:outputScript target =body> 
var focus ='#{focus}';

if(focus){
document.getElementById(focus).focus();
}
< / h:outputScript>

JSF实用程序库 OmniFaces 有一个可重复使用的组件, < o:highlight> (源代码 here 并展示演示此处)。它另外还在无效的输入上设置了一个styleclass,以便你可以通过CSS指定不同的背景颜色。


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.

解决方案

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.

这篇关于在验证错误时将焦点设置为inputText的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆