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 derfloh on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Use one checkbox to show/hide more than one element 1

Status
Not open for further replies.

rockyroad

Programmer
Feb 22, 2003
191
US
Hi,

I have a script and have seen several scripts that use one checkbox, that can show/hide a <div> or other element... does anyone know how to apply similar code to allow multiple elements to to be shown/hidden when toggle checkbox on/off?

Thanks,

RR
 
Code:
function toggle(){
  item1 = document.getElementById('item1');
  item2 = document.getElementById('item1');
  item3 = document.getElementById('item1');
  if(document.forms['myform'].elements['mycheckbox'].checked == true){
    item1.style.display = '';
    item2.style.display = '';
    item3.style.display = '';
  } else {
    item1.style.display = 'none';
    item2.style.display = 'none';
    item3.style.display = 'none';
  }
}
Code:
<form id="myform"><input type="checkbox" id="mycheckbox"></form>
<div id="item1">item1</div>
<div id="item2">item2</div>
<div id="item3">item3</div>

_______________
_brian.
 
tried to do this too fast, i guess. The javascript should be:
Code:
function toggle(){
  item1 = document.getElementById('item1');
  item2 = document.getElementById('item2');
  item3 = document.getElementById('item3');
  if(document.forms['myform'].elements['mycheckbox'].checked == true){
    item1.style.display = '';
    item2.style.display = '';
    item3.style.display = '';
  } else {
    item1.style.display = 'none';
    item2.style.display = 'none';
    item3.style.display = 'none';
  }
}

_______________
_brian.
 
Thanks, is there a way to grab the form by name, rather than ID?
 
If you're calling the function from within the form, say on an onClick event or with an href, simply using toggle(this.form); will pass the name of the form into the function. You'd have to modify the toggle function to accept a variable:
Code:
function toggle(f){
  if(f.elements['mycheckbox'].checked == true){
    f.item1.style.display = 'block';
    f.item2.style.display = 'block';
    f.item3.style.display = 'block';
  } else {
    f.item1.style.display = 'none';
    f.item2.style.display = 'none';
    f.item3.style.display = 'none';
  }
}
Hope this helps!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top