The Right Way to Include Javascript in Your Drupal Form

harry.pottash's picture

Often clients want a touch of singing dancing javascript magic on one of their drupal forms. It seems like the right way to include that javascript file is to create a module that looks something like this:

function hook_form_alter(&$form, $form_state, $form_id){
  if($form_id == 'form_in_question'){
    drupal_add_js(
      drupal_get_path('module', 'switchback_nodeform') 
        . '/my_custom_javascript.js');
   }
}

But it turns out that this code is subtly flawed. If the user misses a required field, or has any other form error, when the form is re-loaded your javascript will be absent. In order to make sure that your javascript is always available on that form you actually need to write code like this:

function hook_form_alter(&$form, $form_state, $form_id){
  if($form_id == 'form_in_question'){
     $form['some_element']['#after_build'] = array('_load_my_javascript);
   }
}

function _load_my_javascript($element){
    drupal_add_js(
      drupal_get_path('module', 'switchback_nodeform') 
        . '/my_custom_javascript.js');
return($element);
}

This ensures that your javascript will get pulled in, even when the page is reloaded.

Comments

Post new comment

The content of this field is kept private and will not be shown publicly.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd> <pre>
  • Lines and paragraphs break automatically.

More information about formatting options