Monday, November 16, 2009

jQuery Dialog Input Focus

I'm a big believer in setting keyboard focus to the proper input. As a long-time laptop user, I avoid using the mouse wherever possible. It simply slows me down. Save the mice!

Using jQuery UI's dialog to pop up a form, I could not do this for some reason. Here is my code to set input focus in a dialog.


// In event handler
$('#mydialog').open();
$('#myinput').get(0).focus();


And nothing! I tried with many dialog options, and the only thing I could do to make it work, was to eliminate the dialog.

The only thing I can figure is that the dialog itself is setting focus, or blurring my focus. So I fixed this by delaying the focus call using a timer.


// In event handler
$('#mydialog').open();
setTimeout("$('#myinput').get(0).focus();", 500);


Note, times less than 200 ms were not reliable.

1 comment:

Anonymous said...

Hello Jeff,

thank's for the hint: I've had the same problem.

For me
---
var textarea = $dialog.find("#description");
SomeGlobalObj.shouldGetFocus = textarea;
setTimeout("SomeGlobalObj.shouldGetFocus.focus();",500);
---
works, too (without '.get(0)').

Regards,
Stephan