Adding Javascript to a Webform

Last modified: February 14, 2009 - 04:43

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');
        }
      });
    });

Confused

jfinkel - September 23, 2009 - 21:18

I find the instructions in Step 2 to be entirely confusing. I do not know how to parse the section to understand exactly what to do for Drupal 6.

Simpler than you think

tstermitz - October 2, 2009 - 00:52

Instruction 2 says to copy the webform-form.tpl.php file from the webform module directory into your theme directory, and add a single line to it, which tells webform to look in your scripts directory for a file called SCRIPT_NAME.js. This is common in Drupal: Drupal uses the webform-form.tpl.php file in your directory instead of the default file in the module. (You don't want to edit the one in the webform directory, because your changes will be overwritten when they update it).

Instruction 3 says to put your jquery code into the SCRIPT_NAME.js file.

Webform now knows where to find your additional code and automatically includes it on your webform pages.

Yes, you probably have to create a scripts directory in your theme directory, and then upload SCRIPT_NAME.js into it.

Couple of simple jquery examples.

tstermitz - October 2, 2009 - 01:45

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!

help with jquery

skwyer - October 23, 2009 - 14:48

I've got a drupal 6.x site and I've tried putting some code into the webform settings/description. I have two radio buttons and I want certain fieldsets to appear based on which one is selected.

This is what I have and it's not working at all. Can you assist. I'm a php noobie.

<?php
drupal_add_js
(
$(
document).ready(function() {
    if ($(
"#edit-submitted-pdf-art-manuscript-format-check-one-required-select-format-Format-B").val() == "yes") {
      $(
"#webform-component-format_b_details").css("display","block");
    }
    else {
      $(
"#webform-component-format_b_details").css("display","none");
    }
  });
);
?>

Any help would be much appreciated.

Dependent field Components

amb_raph - October 6, 2009 - 08:24

Dependent field Components
amb_raph - October 5, 2009 - 16:14

I'm using webform. I want to Create form that contains the following dependent component.

I want to select a state, which is dependent on the country selected.
example:

Field 1) Select Country (the various country will apear in a list box)
Germany
France
Japan
etc

Field 2) Select State (the various states will appear in a list box, depending on the country selected in Field 1)
i.e (If Germany is selected above, states in Germany will be display in this list box)
(if France is selected, States in France will be displayed in this list box)
etc.

Please It's urgent I'll appreciate all Quick Response.
Thanks

 
 

Drupal is a registered trademark of Dries Buytaert.