...

View Full Version : Show / Hide Div Multiple Div's



1sae
06-22-2010, 10:52 PM
Let me start by saying I'm a noob to JavaScript.

What I'm trying to do for my website is have a select menu that shows the number of div's that's selected. I found a JS that I could do that with, but it only toggles, not change specifically what's selected. So if you click the wrong one, it doesn't work right. Here's what I got:


<body>
<script type="text/javascript">
function toggle_visibility(){
for(var i = 0,len = arguments.length;i < len; i++){
var e = document.getElementById(arguments[i]).style,d = e.display;
e.display = (d == "block") ? "none" : "block";
}
}
</script>

<select name="select" id="select">
<option>0</option>
<option onclick="toggle_visibility('1');" >1</option>
<option onclick="toggle_visibility('1','2');">2</option>
<option onclick="toggle_visibility('1','2','3');">3</option>
<option onclick="toggle_visibility('1','2','3','4');">4</option>
</select><br>
<div id="1" style="display: none;">Test1</div>
<div id="2" style="display: none;">Test2</div>
<div id="3" style="display: none;">Test3</div>
<div id="4" style="display: none;">Test4</div>
</body>

Any help would be appreciated, cause I'm lost.

Old Pedant
06-22-2010, 11:27 PM
Well, for starters, you can't attach an onclick to an <option>. If it works in some browsers, you are lucky. It is not standard and doesn't work in all.

You also should never start an ID with a numeric character. Though it should work using getElementById(), it can have other problems.

So...

Is this what you were after?


<html>
<head>
<script type="text/javascript">
function showSome(sel)
{
var lastOne = parseInt(sel.options[sel.selectedIndex].text);
for ( var i = 1; i <= 4; ++i )
{
document.getElementById("Test"+i).style.display =
i <= lastOne ? "block" : "none";
}
}
</script>
</head>
<body>
<form>
<select name="select" onclick="showSome(this);">
<option>0</option>
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
</select><br>
</form>
<div id="Test1" style="display: none;">Test1</div>
<div id="Test2" style="display: none;">Test2</div>
<div id="Test3" style="display: none;">Test3</div>
<div id="Test4" style="display: none;">Test4</div>
</body>
</html>

1sae
06-22-2010, 11:54 PM
Perfect!

Thanks so much, I just really don't know too much about this, and was just trying to piece other code I found together.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum