Javascript Form How to - Show/hide form controls using RadioButton








Question

We would like to know how to show/hide form controls using RadioButton.

Answer


<!DOCTYPE html>
<!-- <!--from  w ww.  ja v a 2  s . c o m-->
     Example File From "JavaScript and DHTML Cookbook"
     Published by O'Reilly & Associates
     Copyright 2003 Danny Goodman
-->
<html>
<head>
<title>Recipe 8.10</title>
<style rel="stylesheet" id="mainStyle" type="text/css">
html {background-color:#cccccc}
body {background-color:#eeeeee; font-family:Tahoma,Arial,Helvetica,sans-serif; font-size:12px;
    margin-left:15%; margin-right:15%; border:3px groove darkred; padding:15px}
h1 {text-align:right; font-size:1.5em; font-weight:bold}
h2 {text-align:left; font-size:1.1em; font-weight:bold; text-decoration:underline}
.buttons {margin-top:10px}

</style>
<script type="text/javascript">

function togglePurDec(evt) {
    evt = (evt) ? evt : event;
    var target = (evt.target) ? evt.target : evt.srcElement;
    var block = document.getElementById("purchaseDecisionData");
    if (target.id == "purDecFlag1") {
        block.style.display = "block";
    } else {
        block.style.display = "none";  
    }
}

</script>
</head>
<body>
<h1>Hidden Form Sections</h1>
<hr /> 
<form name="survey" ...>
...
<p>3. Do you make purchase decisions for your company?<br>
<input type="radio" id="purDecFlag0" name="purchaseDecision" 
    onclick="togglePurDec(event)">No 
<input type="radio" id="purDecFlag1" name="purchaseDecision" 
    onclick="togglePurDec(event)">Yes 
<div id="purchaseDecisionData" style="display:none; margin-left:20px">
<p>
3a. What is your purchase budget for the current fiscal year?
<select name="PurBudget">
    <option value="">Choose One:</option>
    <option value="1">Less than $50,000</option>
    <option value="2">$50,000-100,000</option>
    <option value="3">$100,000-500,000</option>
    <option value="4">$500,000+</option>
</select>
</p>
<p>
3b. What role do you play in purchase decisions? (check all that apply)<br>
<input type="checkbox" name="purRole1">Research<br>
<input type="checkbox" name="purRole2">Recommend<br>
<input type="checkbox" name="purRole3">Review Recommendations of Others<br>
<input type="checkbox" name="purRole4">Sign Purchase Orders<br>
<input type="checkbox" name="purRole5">None of the above<br>
</p>
</div>
</p>
<p>4. How long have you been at your current employment position?
<select name="emplLen">
    <option value="">Choose One:</option>
    <option value="1">Less than 6 months</option>
    <option value="2">6-12 months</option>
    <option value="3">1-2 years</option>
    <option value="4">2+ years</option>
</select>
</p>
...
</form>
</body>
</html>

The code above is rendered as follows: