Community Documentation

Adding Javascript to a Webform

Last updated February 14, 2009. Created by deviantintegral on December 3, 2008.
Edited by quicksketch. Log in to edit this page.

Webform makes it very simple to add snippets of JavaScript to control the interaction of elements on a form. For example, fieldsets can be automatically opened or closed, or JavaScript validation can be performed.

First, read "THEMING.txt" in the webform module folder for an overview of theming Webform nodes. Then, use the following to add the JavaScript to your form.

  1. Determine the Node ID of the form you wish to add the JavaScript to. If you aren't using the path module, it will be in the URL, such as "node/1". Otherwise, it's quickest just to hover over the node's edit link to see the NID in the URL.
  2. Add the following to template.php in your theme.

    In Drupal 5:

    <?php
    function phptemplate_webform_form_NID ($form) {
     
    drupal_add_js(path_to_theme() . '/scripts/SCRIPT_NAME.js');
      return
    theme('webform_form', $form);
    }
    ?>

    In Drupal 6: Copy the webform-form.tpl.php file to your theme's directory, then add the same line as Drupal 5, but anywhere in the top portion of the file with the other PHP code:

    <?php
      drupal_add_js
    (path_to_theme() .'/scripts/SCRIPT_NAME.js');
    ?>

    Replace NID with the node ID from step 1 and SCRIPT_NAME with the name of your script. Change the path to the script if needed as well. Remember that if you are using a theme with subthemes like Zen to use path_to_subtheme() instead of path_to_theme(). If you want to add your script to all webforms, call your function phptemplate_webform_form, removing the NID potion.

  3. Determine the elements you wish to interact with, and use jQuery to easily modify them. The following example expands a fieldset if either checkbox is enabled.
    $(document).ready(function () {
      $('#edit-submitted-contact-me-newsletter-signup').click(function () {
        if ($('#edit-submitted-contact-me-newsletter-signup').attr('checked') &&
            $('#webform-component-contact_information').is('.collapsed')) {
          Drupal.toggleFieldset('#webform-component-contact_information');
        }
      });

      $('#edit-submitted-contact-me-contact-me').click(function () {
        if ($('#edit-submitted-contact-me-contact-me').attr('checked') &&
            $('#webform-component-contact_information').is('.collapsed')) {
          Drupal.toggleFieldset('#webform-component-contact_information');
        }
      });
    });

Comments

Couple of simple jquery examples.

As a newby to jquery, it took me some effort to figure out how to modify form values. My goal was to automatically insert the date into a date_field on a form, so the user doesn't have to do it. The two following snippets serve as models. In this case, I'm putting the jquery code inline rather than using a script file in my theme (as described above). Click on the "Edit:Configuration" tab, and simply insert the code into the "Webform Settings:Description" box. You have to set the input format to permit php code.

To insert the word "happy" into a webform field called reg_date:

<?php
 
echo "PHP Hello<br>";
 
drupal_add_js(
   
'$(document).ready(function(){   
      // functions here.
      $("#edit-submitted-reg-date").val("happy").fadeIn("slow");
  });'
,
 
'inline'
 
);
?>

This is kind of a stupid example because it is easy to set a default value in webform. But it shows you that the $("#edit-submitted-reg-date") addresses the html element, and the .val("happy") modifies the form field of reg_date. The .fadeIn("slow") shows that you can concatenate these commands with other jquery operations.

The syntax is important; carefully note the usage of ticks, quotes, parentheses and brackets, especially the "$(document).ready(function..." which doesn't end until just before the "...inline...". That is the actual jquery/javascript doing the work. Instead of using the inline mechanism shown here, you could add this javascript to your form via a SCRIPT_NAME.js file as described above.

To insert a year-month-day into the reg-date:

<?php
 
echo "PHP Hello<br>";
 
drupal_add_js(
   
'$(document).ready(function(){

        var currentTime = new Date();
        var month = currentTime.getMonth() + 1;
        var day = currentTime.getDate();
        var year = currentTime.getFullYear();
        var dateString = year + "/" + month + "/" + day;
       
        $("#edit-submitted-reg-date").val(dateString);

    });'
,
 
'inline'
 
);
?>

I couldn't find anywhere in the jquery documentation how to pass in a variable to the val() construct. I don't want to tell you how much time I lost to figure out the simple script shown above!

Tom Stermitz, Denver/Ft Collins Colorado
Denver Drupal Design

path_to_theme

I'm using a Zen-derived theme in Drupal 6.16 and path_to_subtheme resulted in a fatal php error. I read elsewhere (http://drupal.org/node/222934) that path_to_subtheme was no longer valid. I changed it back to path_to_theme and the error was gone.

Same here. Same error on

Same here. Same error on D6.20.

webform-form.tpl.php location in D7 sub-theme

Since the documentation doesn't say where to copy this file, I can say through trial & error that it belongs in the sub-theme's root, e.g., my_subtheme/, not the templates folder, e.g., my_subtheme/templates/.

RTFM for D7!

After struggling with the NID targeting example in a D7 installation, I finally saw the note at the beginning urging me to read THEMING.txt before inserting script. So here's the skinny:

If you want the script to load on a specific form, copy webform-form.tpl.php to your sub-theme's root directory. Rename it webform-form-NID.tpl.php, where NID matches the node ID of your webform. Add:

<?php
  drupal_add_js
(path_to_theme() .'/scripts/SCRIPT_NAME.js');
?>

anywhere in the top portion of the file with the other PHP code. In my case, the script is in my_subtheme/js/ and webform-form-NID.tpl.php is in my_subtheme/, so the correct path is '/js/my_script.js'

Clear the cache & watch the magic!

i have placed the

i have placed the webform-form-NID.tpl in my sub theme, then added the drupal_add_js() with my SCRIPT_NAME.js. and cleared the cache. everything seems to work fine, i can see the js file added to my page but the script doesn´t do anything. i have tried:

$(document).ready(function () {
alert("this is working");
});

to test it but no luck.
Any help would be much much appreciated
Thanks

Are you using Drupal 7?

In Drupal 7.x, jQuery is namespaced. See Managing JavaScript in Drupal 7

jQuery is now namespaced to avoid conflicts with other Javascript libraries such as Prototype. All your code that expects to use jQuery as $ should be wrapped in an outer context like so.

(function ($) {
  // All your code here
}(jQuery));

js-file is not even added to

js-file is not even added to my page.
I renamed webform-form.tpl.php to webform-form-NID.tpl.php and moved it to my theme-directory
cleared the cache, of the browser and website.
No result, what so-ever.
It seems that webform-form-NID.tpl.php hasn't been found...

A little help may be welcome here.

NID should be replaced with

NID should be replaced with the node id of the specific form you are attempting to theme. For example, webform-form-123.tpl.php where 123 is the node id.

How 'bout this approach?

Just add a new textarea field to your Webform content type called "JavaScript Snippets". Then in node-webform.tpl.php, add this:

<?php
if (isset($node->field_javascript_snippets[0])) {
  print
'<script type="text/javascript">' . $node->field_javascript_snippets[0]['value'] . '</script>';
}
?>

Now you can add little JS snippets to webforms right through the node creation form.

a little extra explanation, please?

tried this on a basic page, but the scriptcode is not entered into the basic page. Any idea?

KR

Jan

If you're in Drupal 7 you'll

If you're in Drupal 7 you'll have to dig deeper into the render array. I think it would be something like:

<script type='text/javascript'><?php print $content['field_javascript_snippets']['#items'][0]['value']; ?></script>

How about on submit?

Hi all,

Anybody know how to add a little snippet when you submit a webform? Is the best idea to put it on another page, and then set the webform to go to that page ?

Or is there a way to add it direct to the submit button?

Thanks, Joe

I'm looking for the same. It

I'm looking for the same. It seems that in previous versions of Webform there was an 'Additional processing' field where you could place php or javascript code, I cannot find this field on D7

Page status

No known problems

Log in to edit this page

About this page

Drupal version
Drupal 5.x, Drupal 6.x

Site Building Guide

Drupal’s online documentation is © 2000-2013 by the individual contributors and can be used in accordance with the Creative Commons License, Attribution-ShareAlike 2.0. PHP code is distributed under the GNU General Public License. Comments on documentation pages are used to improve content and then deleted.