2

When my form load I would like to set the focus on the first field in the form. I know I can use jquery to do this by doing $('inout id').focus();. Where would I put this code so that it only runs on a certain form?

Is there a simpler way?

Updated

Using a mixture of smile's answer and clive's comment the code that got it working in the end was:

$form['#attached']['js'] = array('(function ($){$(document).ready(function() { $(".form-item-field-name input").focus()});})(jQuery);' => array( 'type' => 'inline'));
4

You can attach js only to your form. Use hook_form_alter()

function your_module_form_alter(&$form, &$form_state, $form_id) {
  if($form_id == 'my_form'){
  // Add JavaScript file
  $form['#attached']['js'] = array(drupal_get_path('module', 'your_module') . '/your_file.js');

  // Or for inline JavaScript
  $form['#attached']['js'] = array('/* some javascript here */' => array( 'type' => 'inline'));
  }
}
  • Tried $form['#attached']['js'] = array('$(".form-item-field_name input").focus()' => array( 'type' => 'inline')); but no joy – user13134 Apr 30 '13 at 12:47
  • @user13134 Assuming you're using Drupal 7 you need to qualify the $ var: ((function($) { // code using $ })(jQuery);), see Managing JavaScript in Drupal 7 – Clive Apr 30 '13 at 12:49
1

To add the HTML5 autofocus attribute from a module in D7, use this example for the user-login form. However, still not supported on iOS Safari as of this posting date.

function HOOK_form_user_login_alter(&$form, &$form_state, $form_id) {
    //should also add JS focus code for iOS Safari
    $form['name']['#attributes'] = array('autofocus' => '');
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.