Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting focus to a JSF inputtext [duplicate]

Tags:

jsf

I need to direct the input focus to a specific inputtext component upon loading the page (to allow entering a value using a barcode scanner).

In plain HTML I would add a JavaScript "onload" handler to the body tag, but there must be a better way in JSF.

What is the "cleanest" way to achieve this for:

  1. "static" cases where the same control receives focus every page load.
  2. "dynamic" cases where this could be a different control for every page load.
like image 625
Timo Avatar asked Oct 09 '09 07:10

Timo


People also ask

How to set focus on input text box in JavaScript and jQuery?

This post will discuss how to set focus on the input text box in JavaScript and jQuery. 1. Using jQuery. With jQuery, you can use the .focus() method to trigger the “focus” JavaScript event on an element. This method is a shortcut for .trigger("focus") method.

How do you use input text in JSF?

JSF <h:inputText>Tag The JSF <h: inputText> tag is used to render an input field on the web page. It is used within a <h: form> tag to declare input field that allows user to input data. The value attribute refers to the name property of a managed bean named User.

How do I give focus to a text field?

The focus () method is used to give focus to a text field. Tip: Use the blur () method to remove focus from a text field. None. Thank You For Helping Us! Your message has been sent to W3Schools.

How do I focus an HTML element in a form?

The PR #23316 introduced ElementReference.FocusAsync () which is convenient to focus an html element. In my case I need to focus an <InputText> component in a form. There are 2 cases where I want to focus the element: I currently use a custom component that inherits from InputText and provide a FocusAsync method.


1 Answers

Interesting question.

There is nothing out of the box in JSF to do this. You already know how to do this in plain HTML/Javascript and there is nothing different that JSF adds to this other than it's crazy IDs.

So for "static" access you just have to ensure that you specify the full JSF ID eg. "myform:mydiv:myinput". This isn't very clean though as if your page changes then it's likely that this ID will also change.

Ideally you'd have a JSF component that you'd nest inside your <h:inputText> that would indicate that focus was required. For example:

<h:inputText value="#{whatever}">
  <my:focusComponent />
</h:inputText>

Technically, it wouldn't be a hard solution. The component would just find it's ID and then add some javascript that calls focus() on it.

Seam has something similar with it's <s:defaultAction/> component that makes a link or button respond to the enter key. You may want to check out the source code of that.

like image 170
Damo Avatar answered Sep 18 '22 18:09

Damo