开发者

Set focus to specific JSF inputText on page load

开发者 https://www.devze.com 2023-01-04 22:07 出处:网络
I want to set f开发者_如何学Pythonocus 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 i

I want to set f开发者_如何学Pythonocus 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:

  • Set focus to inputText on validation error
  • Calling a JavaScript function from managed bean

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:

  • OmniFaces highlight does not set focus with <p:ajax>


If you use primefaces, you can focus your input like this:

<p:focus for="inputId"/>
0

精彩评论

暂无评论...
验证码 换一张
取 消