19

I want to set focus on inputText field in JSF on page load. How can I implement this?

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
MohammedYakub M.
  • 2,893
  • 5
  • 31
  • 42

2 Answers2

30

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:

Community
  • 1
  • 1
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
21

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

<p:focus for="inputId"/>
John Alexander Betts
  • 4,718
  • 8
  • 47
  • 72
  • Note that using this in a panelGrid will mess with the positioning... Place it outside... But then it seems to have to be inside the same form or something, so watch for that as well... – Andrew Nov 14 '17 at 23:08