Drupal form default input focus

Drupal form FAQ: How do I get default input focus on a Drupal form field (presumably a form textfield)?

There may be a better way to do this, but here's what I just did to get default input focus on a series of Drupal form 'add' and 'edit' pages. I just included the following Drupal form suffix definition on any form where I wanted to control the default input focus:

$form['#suffix'] = '<script type="text/javascript">'
                 . 'jQuery(\'input#edit-name\').focus();'
                 . '</script>';

In this case I had a 'name' field defined something like this:

$form['name'] = array(
  '#type' => 'textfield',
  '#title' => t('Name'),
  '#required' => TRUE,
  '#description' => "A name for your widget",
  '#weight' => 10,
);

This results in a text field being rendered in my form something like this:

<input type="text" id="edit-name" name="name" value="" class="form-text required" /> 

As a result, the JavaScript/jQuery focus function call shown earlier matches up with the 'edit-name' id tag of my form's textfield. I've made the 'edit-name' fields bold so you can see them a little more easily.

As mentioned, there may be other and better ways to put default input focus on a field in a Drupal form, but this approach does work. (I've used other approaches with CSS and jQuery using Java and CakePHP, but this seems to work well for Drupal forms.)

Post new comment

The content of this field is kept private and will not be shown publicly.