Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How to Show/Hide form fields whenever I select/unselect a checkbox?

Forms

How to Show/Hide form fields whenever I select/unselect a checkbox?

by  medic  Posted    (Edited  )
Try these code samples:
1) Make an HTML page and place this script inside the HEAD tag:
[color blue]
Code:
<script language="JavaScript">
  function showhidefield()
  {
    if (document.frm.chkbox.checked)
    {
      document.getElementById("hideablearea").style.visibility = "visible";
    }
    else
    {
      document.getElementById("hideablearea").style.visibility = "hidden";
    }
  }
</script>
[/color]
2) Put the following code inside the BODY tag:
[color blue]
Code:
 <form name='frm' action='nextpage.asp'>
  <input type="checkbox" name="chkbox" onclick="showhidefield()">
  Check/uncheck here to show/hide the other form fields
  <br>
  <div id='hideablearea' style='visibility:hidden;'>
    <input type='text'><br>
    <input type='submit'>
  </div>
  This is a text line below the hideable form fields.<br>
</form>
[/color]
All items inside the DIV tags appear/disappear as you select/unselect the checkbox.
Notice that the line of text below the hideable area stays on the same place whether the
checbox is selected or unselected.

Now, what if we want everything below the hideable area move up to fill-in the gap or unused space
when the area is hidden? Very simple. We just have to make a few changes in our HTML sample:

1) Change some portions of the javascript to make it look like this:
[color blue]
Code:
<script language="JavaScript">
  function showhidefield()
  {
    if (document.frm.chkbox.checked)
    {
      document.getElementById("hideablearea").style.display = "block";
    }
    else
    {
      document.getElementById("hideablearea").style.display = "none";
    }
  }
</script>
[/color]

2) Now, replace the style attribute of the DIV tag with [color blue]style='display:none'[/color].
Test your modified HTML.
Notice that all items below the hideable area move up to fill-in that gap left by the area when it is hidden.
Register to rate this FAQ  : BAD 1 2 3 4 5 6 7 8 9 10 GOOD
Please Note: 1 is Bad, 10 is Good :-)

Part and Inventory Search

Back
Top