tags:

views:

584

answers:

1

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.
+1  A: 

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.

Damo
I like your dynamic solution. It has some limitations if the control to focus moves all over the place, but it suffices in my situation. Thanks!
Timo