dev@javaserverfaces.java.net

Re: Setting focus on input fields

From: Jim Driscoll <Jim.Driscoll_at_Sun.COM>
Date: Mon, 07 Apr 2008 16:02:51 -0700

Well, I wanted to write a custom component anyway... to continue my
exploration of JSF. So, I've been pondering this and writing little
example programs. But I came up blank as to how one would do the
following:

Jason Lee wrote:
> This might be nice too:
> <h:inputText><foo:focus/></h:inputText> (with the last one winning, if
> the page author has several for some reason)

The problem with this, is that you don't get to write out the javascript
after the inputText is rendered - only before. But you need the id to
exist before you can set a focus on it. So I'm stumped as to how to do
simple seeming example. I imagine you'd have to do all kinds of painful
things with Phaselisteners and stream parsing. Ouch.

If you could, in a simple fashion, queue the javascript for the end of
the page when you hit a tag, that would solve things... but that's 2.0
stuff, right? Or is that going to even be possible in 2.0?


> <foo:focus element="form1:firstName" /> (for a specific element)

Hmm. I've been thinking about this - don't most id crossreferences only
use same-form id's? It would probably be less confusing to the enduser
to embed it into a form and do a <foo:focus for="componentID" /> rather
than have it be outside the form and do a <foo:focus
for="formID:componentID" />

Implementation of this version is trivial - I had it done in about an
hour (which is why I started it as my first component effort).

> <foo:focus /> (to grab the element on the page with the lowest tab index)

This should be doable with a fairly straightforward script in
JavaScript, but it would seem less useful than the qualified version.
Maybe as a default action for the focus tag without a "for" attribute?
But that would also mean that you'd have to set tabindex for all the
fields, which doesn't seem like common practice for simple forms (and
for more complex forms, you're probably doing javascript anyway, and
don't need this tag).

If you don't mind, Jason, I'd like to have a crack at just doing a
version for 1.2 with the <mj:focus for="componentID"/> format... Then
we can tweak it. In particular, if you have an insight on how to emit
javascript at the right time with a wrapping inputText tag, I'd love to
know even if you don't think you have time - it's going to bother me
until I figure out how.


And of course, for all of this, we're talking about 1.2.

For 2.0, I agree with Jacob that it makes most sense to have it be an
attribute of f:view... i.e. <f:view focus="formID:clientID">

Jim