Load Javascript Conditionally Based on Form Value I have two different kinds of webforms, one I'll call "type 1" and one I'll call "type 2". Depending on the type of webform, I want to conditionally add either type1.js or type2.js. The type of webform is has a hidden field called formtype that an admin would set either to "type1" or "type2," and then, theoretically, I would pull in the proper Javascript based on that value when the form loads.

My hook_form_alter() function looks like this:

&lt;?php
/**
 * Implements hook_form_alter().
 */
function module_name_form_alter(&amp;$form, $form_state, $form_id) {
  if($form['submitted']['formtype']['#default_value'] == 'type1'){
    drupal_add_js($js_path . 'type1.js');
  }
  elseif($form['submitted']['formtype']['#default_value'] == 'type2'){
    drupal_add_js($js_path . 'type2.js');
  }
}
?&gt;


This does actually cause the proper javascript to load, but I get a Drupal message saying:

Undefined index: submitted (etc.)


My question is: why would I be receiving this error message even though the logic appears to work? I'm also open to other ways of handling this use-case.

FYI, I'm using Drupal 7.
You applied this code for all forms on your site, but only webform has $form['submitted'] element. To fix this issue you may use next code snippet

&lt;?php
/**
 * Implements hook_form_alter().
 */
 function module_name_form_alter(&amp;$form, $form_state, $form_id) {
   if (!empty($form['submitted'])) {
     if ($form['submitted']['formtype']['#default_value'] == 'type1'){
       drupal_add_js($js_path . 'type1.js');
     }
     else if ($form['submitted']['formtype']['#default_value'] == 'type2'){
       drupal_add_js($js_path . 'type2.js');
     }
  }
}
?&gt;