The Right Way to Include Javascript in Your Drupal Form
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.
Recent posts
- Congratulations To GLEAM On Their Award!
- Extending Personal Campaign Pages
- Switchback is hiring!
- Congratulations to the University of Michigan’s Open Courseware Initiative!
- Basics of Drupal Quickbooks Integration
- Using your own fonts with @font-face in Drupal Gardens
- Drupal 7 is here! Commence Rejoicing!
- We're proud to be part of the Open.Michigan project
- AdaptiveTheme with a Sticky Footer and Skinr Styles
- Ann Arborists and Drupalists!
Caravan is a powerful and full-featured membership management system, designed specifically for membership- driven organizations.
Trailhead is a Drupal-based system, built with the features smaller businesses need, bundled together into a ready-to-launch package.
Our Work
On the Trail Blog
-
We are thrilled to share that one of our...
-
Steve was recently invited to write a...
-
We have some really exciting projects in...
Comments
Thanks for the code. I think this is a good method, but it might be worth mentioning that Damien Tournoud described it as "makes little sense" on http://drupal.org/node/322290.
I normally use the method mentioned by Damien Tournoud, but when I've no need to retheme the form aside from trying to include a js or css file, I find the method mentioned here far faster/easier to implement.