PDA

View Full Version : Act on changed dropdownList


xaphod
09-16-2003, 12:19 PM
Hi,
I have a dropdownlist and when a new selection is made I want to - based on the selection - show a second dropdownList.

Is this possible in JavaScript?

regards /xaphod

glenngv
09-16-2003, 12:48 PM
try this...


<html>
<head>
<script type="text/javascript">
function showSub(mainSel){
var f = mainSel.form;
var s,i=1;
var targetId = mainSel.options[mainSel.selectedIndex].value;
for (s=document.getElementById('sub'+(i++))){
s.style.display = (s.id==targetId) ? 'inline':'none';
}
}
</script>
</head>
<body>
<form>
<select name="combo1" onchange="showSub(this)">
<option value="">Choose item</option>
<option value="sub1">Sub 1</option>
<option value="sub2">Sub 2</option>
<option value="sub3">Sub 3</option>
</select>
<span id="sub1" style="display:none">
<select name="subcombo1">
<option>subcombo1</option>
</select>
<span id="sub2" style="display:none">
<select name="subcombo2">
<option>subcombo2</option>
</select>
<span id="sub3" style="display:none">
<select name="subcombo3">
<option>subcombo3</option>
</select>
</span>
</form>
</body>
</html>


though not tested :p

xaphod
09-16-2003, 02:36 PM
Hi Glenn,
I can't get your code to work for me, could you please take a quick look trying to debug?

regards /xaphod

glenngv
09-17-2003, 06:15 AM
Sorry, I've mixed the for loop and the while loop :o
The loop should have been

while ( s=document.getElementById('sub'+(i++)) )

but even so, it won't still work. :o
I'll try to fix it later if someone will not beat me into it.

glenngv
09-17-2003, 08:37 AM
Here's the fix:


<html>
<head>
<script type="text/javascript">
function showSub(mainSel){
var f = mainSel.form;
var s,i=1;
var targetId = mainSel.options[mainSel.selectedIndex].value;
while ( s=document.getElementById('sub'+(i++)) ) {
s.style.display = (s.id==targetId) ? '':'none';
}
}
</script>
</head>
<body>
<form>
<select name="combo1" onchange="showSub(this)">
<option value="">Choose item</option>
<option value="sub1">Sub 1</option>
<option value="sub2">Sub 2</option>
<option value="sub3">Sub 3</option>
</select>
<span id="sub1" style="display:none">
<select name="subcombo1">
<option>subcombo1</option>
</select>
</span>
<span id="sub2" style="display:none">
<select name="subcombo2">
<option>subcombo2</option>
</select>
</span>
<span id="sub3" style="display:none">
<select name="subcombo3">
<option>subcombo3</option>
</select>
</span>
</form>
</body>
</html>


Earlier, I missed the closing span tags in the 1st and 2nd spans.

xaphod
09-17-2003, 02:34 PM
Thanxs Glenn!
You are my hero! :)

regards /xaphod