Magazine Subscriptions - Myspace Layouts - Loan - Loans - Coin Community

PDA

View Full Version : Hide/Show Set of Divs using a checkbox.


Skinny
Feb 2nd 2008, 12:25 pm
Hey guys Okay I'm looking to hide a set of divs.

Let's say I have an unknown amount of divs that all share the same id (so that they can be hid and shown at the same time).

So I want a checkbox that will toggle them all on or off (checkbox will be checked initially).

How do I build this.

So far I have this code here as an example but it's not working (and the checkbox isn't checked at the start.


<head>
<script type="javascript">
function toggle(ID) {
var el = document.getElementById(ID);
if ( el.style.display != 'none' ) {
el.style.display = 'none';
}
else {
el.style.display = '';
}
}
</script>
</head>
<body>

<form>
<input type="checkbox" onClick="toggle(descr);"> See Descriptions
</form>

<div id="descr">Hello This is #1</div>
<div id="descr">Hello This is #2</div>
<div id="descr">Hello This is #3</div>
</body>

ToddMicheau
Feb 2nd 2008, 1:06 pm
Hello, I've updated your code to what I think you were after. It will show/hide a div block based on the ID passed to the Toggle function.


<head>
</head>
<body>
<script language="javascript">
function toggle(divId) {
var divArray = document.getElementsByTagName("div");
for(i = 0; i < divArray.length; i++){
if(divArray[i].id == divId){
if(divArray[i].style.display != 'none'){
divArray[i].style.display = 'none';
}else{
divArray[i].style.display = '';
}
}
}
}
</script>
<form>
<input type="checkbox" checked onClick="toggle('descr');"> See Descriptions
</form>

<div id="descr">Hello This is #1</div>
<div id="descr">Hello This is #2</div>
<div id="descr">Hello This is #3</div>
<div id="non-descript">Hello This is not one of them</div>
</body>

locdev
Feb 2nd 2008, 4:43 pm
better don't use the same ids.
use an array of IDs you want to show/hide and with prototypejs framework it is 3 lines of code.