The Right Way to Include Javascript in Your Drupal Form

Submitted by harry.pottash on 13 January, 2010 - 17:04
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.
Search
Recent posts
- Two brand new Drupal websites: Kelleher Badges & Long Wing
- Working with multi-select boxes in jQuery
- How to Tame The Zen Ninesixty Theme
- New Websites for Kalamazoo Public Schools & SIGGRAPH Asia
- The Right Way to Include Javascript in Your Drupal Form
- Two website relaunches: Economic History Association & LaRaedo
- A Brief Discourse on Morale and Web Development (Continued)
- Switchback is hiring!
- Drupal Breadcrumb Fun!
- Caravan—Membership Management for Active Organizations





Comments
Post new comment