I want to add JavaScript code to a webform. For example, to add things like onclick, onchange, mouseover function to webform's textbox, textarea, select, email, etc.

How do I do so?


The recommended way to add a JS to any form in Drupal is using #attached to the $form element.

In order to add the JS to a webform, you would have to implement hook_form_alter or hook_form_FORM_ID_alter, and add the #attached

function MODULE_form_webform_client_form_3_alter(&$form, &$form_state) {
  $form['#attached']['js'] = array(
    drupal_get_path('module', 'MODULE') . '/MODULE.js',

Then create the MODULE.js file inside the module directory, and write your JS there.

Refer to The Drupal JavaScript API, to see how to work with JS in Drupal way.

|improve this answer|||||
  • Thank for reply. I wonder is there any basic tutorial for me to learn this? – peifa May 26 '15 at 8:41

To load a script on a specific form , follow the following steps:

  1. Copy webform-form.tpl.php to your sub-theme's root directory.
  2. Rename it webform-form-NID.tpl.php, where NID is the node ID of your webform.
  3. Add the following code in above created theme file:

drupal_add_js(path_to_theme() .'/scripts/SCRIPT_NAME.js');

|improve this answer|||||

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.