Web design, programming, graphics, and pretty much anything else I care about.

Javascript for showing and hiding form fields based on the value of another field

This is the rather long js for making a block of fields only appear if a specific value was chosen for another field. (It made address information appear if you chose "General Public" on a registration form.) It is added as a markup field in a webform.

<?php
drupal_add_js
(
 
'//functions to show/enable and hide/disable specific fieldset
    function showValues(){
        $("#webform-component-address").show();
        $("input[name=\'submitted[address][address_line_1]\']").removeAttr("disabled");
        $("input[name=\'submitted[address][address_line_2]\']").removeAttr("disabled");
        $("input[name=\'submitted[address][city]\']").removeAttr("disabled");
        $("input[name=\'submitted[address][state]\']").removeAttr("disabled");
        $("input[name=\'submitted[address][zip_code]\']").removeAttr("disabled");
        $("label[for=\'edit-submitted-address-address-line-1\']").append(\'<span class="form-required" title="This field is required.">*</span>\');
        $("label[for=\'edit-submitted-address-city\']").append(\'<span class="form-required" title="This field is required.">*</span>\');
        $("label[for=\'edit-submitted-address-state\']").append(\'<span class="form-required" title="This field is required.">*</span>\');
        $("label[for=\'edit-submitted-address-zip-code\']").append(\'<span class="form-required" title="This field is required.">*</span>\');
    }
    function hideValues(){
        $("#webform-component-address").hide();
        $("input[name=\'submitted[address][address_line_1]\']").attr("disabled","disabled");
        $("input[name=\'submitted[address][address_line_2]\']").attr("disabled","disabled");
        $("input[name=\'submitted[address][city]\']").attr("disabled","disabled");
        $("input[name=\'submitted[address][state]\']").attr("disabled","disabled");
        $("input[name=\'submitted[address][zip_code]\']").attr("disabled","disabled");
        $("label[for=\'edit-submitted-address-address-line-1\'] span").remove();
        $("label[for=\'edit-submitted-address-city\'] span").remove();
        $("label[for=\'edit-submitted-address-state\'] span").remove();
        $("label[for=\'edit-submitted-address-zip-code\'] span").remove();
    }
    $(document).ready(function(){
      $("select[name=\'submitted[affiliation]\']").change(function(){
        if(this.selectedIndex==6) {
          showValues();
        }
        else {
          hideValues();
        }
      });
    });'  
 
,'inline'
);

drupal_add_js (
 
'$(document).ready(function(){  
       var selval = $("select[name=\'submitted[affiliation]\']");
       if(selval.val()=="General Public") {
         showValues();
       }
       else {
         hideValues();
       }
   });'
 
,'inline'
);
?>