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

06-22-2010, 11: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:

<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";

<select name="select" id="select">
<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>
<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>

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

Old Pedant
06-23-2010, 12:27 AM
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.


Is this what you were after?

<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";
<select name="select" onclick="showSome(this);">
<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>

06-23-2010, 12:54 AM

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