Ice Cream
- Use JavaScript to add the "onclick" listener
- Use JavaScript to hide the
div
containing the additional options.
Let's see how we can do this with jQuery. Items to note:
- Separation. The "click" handler is bound via JavaScript and not the onclick attribute.
- Fancier. jQuery provides many "effects" and "animations" (basic ones here are
fadeOut
andfadeIn
)
<form method="get" name="ice_cream" id="ice_cream" action="https://cscie12.dce.harvard.edu/echo">
<div>Would you like ice cream?
<br/>
<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>How would you like it?
</p>
<label>
<input type="radio" id="container_cup" name="container" value="cup"/>
Cup </label>
<br/>
<label>
<input type="radio" id="container_cone" name="container" value="cone"/>
Cone </label>
<br/>
<p>Pick your toppings:
</p>
<label>
<input type="checkbox" name="toppings" id="toppings_wc" value="whipcream"/>
Whipped cream </label>
<br/>
<label>
<input type="checkbox" name="toppings" id="toppings_j" value="jimmies"/>
Jimmies </label>
<br/>
<label>
<input type="checkbox" name="toppings" id="toppings_nuts" value="nuts"/>
Nuts </label>
<br/>
<label>
<input type="checkbox" name="toppings" id="toppings_cherry" value="cherry"/>
Cherry </label> </fieldset>
<p>
<input type="submit"/>
</p>
</form>
In style
element
(<style>
) within head
element:
#icecream_options {
background-color: #eee;
margin-left: 2em;
}
label { display: block; }
In
script
element within head
element (<script>
):
$(document).ready(
function(){
$("#icecream_options").hide();
$("input[name='want']").click(
function(){
displayIceCreamOptions();
}
);
}
);
function displayIceCreamOptions() {
if ($("input[name='want']:checked").val() == 'yes') {
$('#icecream_options').fadeIn('slow');
} else {
$('#icecream_options').fadeOut('slow');
}
}