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.

There are generally two ways of adding JavaScript, inline or to the header of the page. The inline approach is easier, but inline JavaScript may slow down the rendering of the page as it gets executed while the page is loading. Adding JavaScript to the page header allows it to be executed after the page has finished rendering.

Inline JavaScript

For inline JavaScript, you only need to add a "Markup" component to your Webform. This allows you to enter any HTML code you want (including JavaScript) to the form. Add a new Markup component from the "Webform" tab with a label like "Custom JavaScript". Then in the text area for the content of the markup, enter your JavaScript surrounded by <script> tags such as this:

<script>
  alert('hello!');
</script>

Finally, make sure that your selected input format (usually Full HTML) won't filter out the script tag on output. You may need to be an administrator to use this option.

Adding JavaScript to the page header

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. Copy the webform-form.tpl.php file from the webform/templates directory to your theme's directory. If you want to theme one particular form, rename the file to "webform-form-NID.tpl.php" (where NID is the node's ID). In the top portion of the file add a line like this:

      drupal_add_js(path_to_theme() .'/scripts/SCRIPT_NAME.js');
    
  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');
        }
      });
    });
  4. In order for your new tpl.php file to have an effect, you must clear your Drupal caches on the Performance page of the admin interface.

Comments

tstermitz’s picture

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 Colorado

todorojo’s picture

Thanks! This really helped.

ealtman’s picture

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.

NickWebman’s picture

Same here. Same error on D6.20.

Anonymous’s picture

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/.

Anonymous’s picture

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:

  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!

cinco5s’s picture

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

jenna.tollerson’s picture

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));
oholender’s picture

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.

charlie-s’s picture

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.

charlie-s’s picture

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.

jrr_cn’s picture

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

charlie-s’s picture

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>

joecanti’s picture

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

federico’s picture

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

d8v15’s picture

I need to add js to the page (which calls the api on anothe rserver) on successful form submit. I will need some of the info from the form (e.g. user name, email, etc).

I am unable to find the hook (if any) or a thorough example.

Anybody’s picture

http://www.DROWL.de || Professionelle Drupal Lösungen aus Ostwestfalen-Lippe (OWL)
http://www.webks.de || webks: websolutions kept simple - Webbasierte Lösungen die einfach überzeugen!
http://www.drupal-theming.com || Individuelle Responsive Themes