How to set input focus on an INSERTED form in Drupal?

1k Views Asked by At

I've got some code that uses the regular Forms API to put together a simple form. I'm using the jQuery Tools package to generate this form and insert it into an overlay. This is working fine, but I'd like to have the input focus set to a text field in the form once it's exposed. I've tried tacking some jQuery code that should do it -- <script type='text/javascript'>$('#textfieldID').focus();</script> -- or somesuch onto the end of the form in the form's theming function, but it's not getting loaded onto the page. I'm guessing this is because some part of Drupal is being "helpful" and filtering out the script, but I'm not really certain. In any case, the code's not getting run -- if I insert a javascript alert() statement as part of the code, nothing happens.

Any advice out there? I'd really like to get the focus set on this guy. Thanks!

3

There are 3 best solutions below

1
On BEST ANSWER

I'm declaring this to be "answered" -- after digging deeper (= blood on the keyboard), it's now clear to me that jQuery Tools is the culprit here -- the form, as created by Drupal, definitely contains whatever scripting stuff I insert into it (latest scheme: a $(document).ready(...focus...) as a markup element in the form). Somewhere in making its way through the jQT overlay process, the scripting goes away. The main hint: If I disable the overlay such that the form comes up in a regular page, the script is present, runs, and correctly sets the focus.

Blurg; at least I (think I) know what's going on -- even though it's not working, I've got a better question to ask. Thanks to all for the help along the way.

2
On

You should be able to do drupal_add_js in the form theme functions, but I would need to see your code.

This works for me:

mymodule_init() {
   if (request_uri() == 'path where your form resides') {
      drupal_add_js(arguments);
   }
}

If you have a multistep form, you can do this:

mymodule_init() {
   if (preg_match('/path/', request_uri())) {
      drupal_add_js(arguments);
   }
}

You might want to use drupal_match_path instead of preg_match above, but I have been unsuccessful in getting that to work for this scenario.

http://api.drupal.org/api/drupal/includes--common.inc/function/drupal_add_js/6

3
On

You should use Drupal's api to include the JavaScript, using drupal_add_js. Doing it in the form's theming function is the way to go, since it would be called, even if the form is cached.

Drupal won't filter out script tags etc, so if they aren't printed, it sounds like you are doing something wrong in your theming function.