You are here

function focus_form_alter in Autofocus 7

Same name and namespace in other branches
  1. 5 focus.module \focus_form_alter()
  2. 6 focus.module \focus_form_alter()

Implements hook_form_alter().

Add javascript (jQuery) to set focus on the first field in the defined forms.

File

./focus.module, line 96
Simple module that sets focus on the first field in a form.

Code

function focus_form_alter(&$form, &$form_state, $form_id) {
  static $add_js = TRUE;

  // Get defined forms.
  $focus_forms = variable_get('focus_forms', FOCUS_FORMS);

  // Replace !content_type! with the current node type.
  if (isset($form['type']['#value'])) {
    $focus_forms = strtr($focus_forms, array(
      "!content_type!" => $form['type']['#value'],
    ));
  }
  $focus_forms = preg_split("/[\\s,]+/", $focus_forms);
  if ($add_js && in_array($form_id, $focus_forms)) {

    // Treat the user login form as a special case (otherwise
    // OpenID, if enabled,  will break it).
    if ($form_id == 'user_login') {
      $selector = '#edit-name';
    }
    else {
      $selector = '#' . $form['#id'] . ' :input:visible:enabled:first';
    }
    $jquery_snippet = 'jQuery(document).ready(function(){var i = jQuery("' . $selector . '");if (i.val() == "") {i[0].focus();}});';
    drupal_add_js($jquery_snippet, 'inline');

    // Don't add javascrip for another form.
    $add_js = FALSE;
  }
}