Javascript Form How to - Show/hide a text field/select option by selecting a radio button option








Question

We would like to know how to show/hide a text field/select option by selecting a radio button option.

Answer


<html>
<head>
<script type="text/javascript">
  function Reveal(it, box) {<!--from  ww w . j a va  2  s.  c  o  m-->
    var vis = (box.checked) ? "block" : "none";
    document.getElementById(it).style.display = vis;
  }

  function Hide(it, box) {
    var vis = (box.checked) ? "none" : "none";
    document.getElementById(it).style.display = vis;
  }
</script>
</head>
<body>
  <form>
    <input type="radio" name="mype" value="ve1"
      onClick="Hide('div2', this); Reveal('didfv1', this)" />value1 <input
      type="radio" name="mype" value="value2"
      onClick="Hide('didfv1', this); Reveal('div2', this)" />value2 <input
      type="checkbox" name="modtype" value="value3"
      onClick="Reveal('div3', this)" />value3 <input type="checkbox"
      name="modtype" value="value4" onClick="Reveal('div4', this)" />value4
    <input type="checkbox" name="modtype" value="value5"
      onClick="Reveal('div5', this)" />value5
  </form>
  <div class="row" id="didfv1" style="display: none">Show Div 1</div>
  <div class="row" id="div2" style="display: none">Show Div 2</div>
  <div class="row" id="div3" style="display: none">Show Div 3</div>
  <div class="row" id="div4" style="display: none">Show Div 4</div>
  <div class="row" id="div5" style="display: none">Show Div 5</div>
</body>
</html>

The code above is rendered as follows: