在页面加载时将焦点设置为特定的JSF inputText [英] Set focus to specific JSF inputText on page load
问题描述
我想在页面加载时将焦点设置在JSF中的inputText字段上。如果你已经在HTML5和JSF 2.2,使用HTML5 自动对焦
属性。在JSF 2.2中,您可以将其设置为直通属性。
< html ... xmlns:a =http://xmlns.jcp.org/jsf/passthrough> ;
...
< h:inputText ... a:autofocus =true/>
你甚至可以有条件地设置它,你只需要确保 false 条件的计算结果为
null
,否则该属性将仍然呈现。这是一个HTML布尔属性,所以只有它的存在已经是触发器,而不管它的值。当值显式设置为 null
时,那么JSF将不会呈现整个属性。
< h:inputText ... a:autofocus =#{component.valid?null:true}/>
另一种方法是引入一些JavaScript。每个输入元素都有一个 focus()函数。以下天真的Vanilla JS方法将第一个表单的第一个元素作为焦点。
window.onload = function(){
document.forms [0] .elements [0] .focus();
$ b $ p
$ b 如果你想在窗口加载时关注一个特定的输入元素,
window.onload = function(){
document.getElementById('formId:inputId')。 ;
$ b $ p
$ b如果你碰巧拥有jQuery,那么可以进行更细粒度的检查。
$(document).ready(function(){
$(:input:visible:enabled:第一个)。focus()
});
如果您打算在回传后执行此操作,请前往以下相关的问答:
- 在验证错误上将焦点设置为inputText 从托管bean调用JavaScript函数
实用程序/组件库可能具有内置自动对焦设施。 OmniFaces 有一个 < o:highlight>
,其中突出显示回发时的所有无效输入,并自动聚焦第一个。默认情况下, PrimeFaces 会在完成ajax请求时自动聚焦last active元素,并具有 < p:focus>
了解更多细粒度的控制。另请参阅下面相关的问答:
使用< p:ajax> 设置焦点
I want to set focus on inputText field in JSF on page load. How can I implement this?
解决方案 If you're already at HTML5 and JSF 2.2, use HTML5 autofocus
attribute. In JSF 2.2 you can set it as a passthrough attribute.
<html ... xmlns:a="http://xmlns.jcp.org/jsf/passthrough">
...
<h:inputText ... a:autofocus="true" />
You can even conditionally set it, you only need to make sure that the false
condition evaluates to null
, otherwise the attribute will still be rendered. It's a HTML boolean attribute, so only its presence is already the trigger regardless of its value. When the value is explicitly set to null
, then JSF won't render the attribute in its entirety.
<h:inputText ... a:autofocus="#{component.valid ? null : true}" />
An alternative would be to throw in some JavaScript. Every input element has a focus() function. The below naive Vanilla JS approach focuses the first element of the first form.
window.onload = function() {
document.forms[0].elements[0].focus();
}
If you want to focus a specific input element during window load, then do:
window.onload = function() {
document.getElementById('formId:inputId').focus();
}
If you happen to have jQuery at hands, more fine grained checks could be done.
$(document).ready(function() {
$(":input:visible:enabled:first").focus()
});
In case you intend to execute it only after a postback, head to below related Q&A:
Utility/component libraries may have builtin autofocus facilities. OmniFaces has a <o:highlight>
which highlights all invalid inputs on postback and autofocuses the first one. PrimeFaces by default autofocuses the "last active" element on complete of an ajax request and has a <p:focus>
for more fine grained control. See also below related Q&A:
这篇关于在页面加载时将焦点设置为特定的JSF inputText的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!