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.
...
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.
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