JavaScript and Ice Cream

Exposing Additional Form Elements

Additional relevant form elements are exposed based upon user input. Here, this is achieved by having the entire form in the markup, with a certain section hidden via CSS (display: none;). If "Yes" is chosen, the display property is changed to "block" through JS.

Example 8.1 - Exposing Additional Form Elements - Example 8.1

 <form method="post" name="ice_cream" id="ice_cream" action="https://cs12.net/form/submit.php">
   <div>Would you like ice cream?
     <label>
       <input type="radio" name="want" id="ic_yes" value="yes"/>
Yes     </label>
     <label>
       <input type="radio" name="want" id="ic_no" value="no"/>
No     </label>
   </div>
   <fieldset id="icecream_options">
     <legend>Ice Cream Options     </legend>
     <p>Cup or a Cone?
     </p>
     <label>
       <input type="radio" id="container_cup" name="container" value="cup"/>
Cup     </label>
     <label>
       <input type="radio" id="container_cone" name="container" value="cone"/>
Cone     </label>
     <p>Pick your toppings:
     </p>
     <label>
       <input type="checkbox" name="toppings" id="toppings_wc" value="whipcream"/>
Whipped cream     </label>
     <label>
       <input type="checkbox" name="toppings" id="toppings_jimmies" value="jimmies"/>
Jimmies     </label>
     <label>
       <input type="checkbox" name="toppings" id="toppings_sprinkles" value="sprinkles"/>
Sprinkles     </label>
     <label>
       <input type="checkbox" name="toppings" id="toppings_nuts" value="nuts"/>
Nuts     </label>
     <label>
       <input type="checkbox" name="toppings" id="toppings_cherry" value="cherry"/>
Cherry     </label>   </fieldset>
   <button type="submit">Submit Order   </button>
 </form>  

In style element (<style>) within head element:

#icecream_options {display:none;
    background-color: #eee;    margin-left: 2em;
} #icecream_options.show { display: block; } label { display: block; }

In script element within head element (<script>):


document.addEventListener("DOMContentLoaded", function() {
  let inputYes = document.getElementById('ic_yes');
  inputYes.addEventListener("click", function() {
    displayIceCreamOptions();
  });

  let inputNo = document.getElementById('ic_no');
  inputNo.addEventListener("click", function() {
    displayIceCreamOptions();
  });
});

function displayIceCreamOptions() {
let divICO = document.getElementById('icecream_options');
let inputYes = document.getElementById('ic_yes');
if (inputYes.checked == true) {
  divICO.classList.add("show");
} else {
  divICO.classList.remove("show");
}
}
 

ice cream options

ice cream options