Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set focus to specific JSF inputText on page load

Tags:

focus

jsf

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

like image 769
MohammedYakub Moriswala Avatar asked Jun 29 '10 10:06

MohammedYakub Moriswala


People also ask

How do I focus a div on page load?

attr("tabindex",-1). focus(); On page load I want divVZITab to become the focus, it is in the center of page. So when page loads IE should automatically scroll to the center of the page & focus on the div.


2 Answers

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>
like image 180
BalusC Avatar answered Sep 28 '22 17:09

BalusC


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

<p:focus for="inputId"/>
like image 36
John Alexander Betts Avatar answered Sep 28 '22 15:09

John Alexander Betts