Maverick Jones
Maverick Jones

Reputation: 434

Hiding a class of Div depending on Select statement option

I'm fairly new to javascript and I'm trying to make an form for my website and I'm stuck on the javascript, This is what I have:

<script type="text/javascript">
function hide(opt) {
if (getElementsByClassName(opt).style.display='none';){
getElementsByClassName(opt).style.display='block';
}
else{
getElementsByClassName(opt).style.display='none';
    }
}
</script>

What I intended the script to do was recieve a variable (the option chosen by the user) and then reveal all the elements with the class of the same name (so if the option was orc the orc div would be displayed, but be hidden if the option chosen was elf etc.) Html:

<form name="chargen" action="" method="post"> 
Name:<Input name="name" type="text" />

Gender:<select name="gender"> 
<option>Choose Gender...</option>
<option>Male</option>
<option>Female</option>
</select>

Species:<select name="species" onchange="hide(document.chargen.species.options[
document.chargen.species.selectedIndex ].value)">
<option> Choose Species...</option>
<option value="human">Human</option>
<option value="orc">Orc</option>
<option value="elf">Elf</option>
<option value="dwarf">Dwarf</option>
<option value="drow">Drow</option>
<option value="ent">Ent</option>
</select>

<div class="human" style="display:none;">
Sub Species:<select name="subspecies1">
<option>Norseman</option>
<option>Hellenic</option>
<option>Heartlander</option>
</select>
</div>

<div class="orc" style="display:none;">
Sub Species:<select name="subspecies2">
<option>Black Orc</option>
<option>Fel Orc</option>
<option>Green Orc</option>
</select>
</div>

<div class="human" style="display:none;">
 Homeland:<select name="homeland1">
<option>Choose Homeland...</option>
<option value="citadel">Citadel</option>
<option value="wildharn">Wildharn</option>
<option value="Merith">Merith</option>
</select>
</div>

<div class="orc" style="display:none;">
Homeland:<select name="homeland2">
<option>Choose Homeland...</option>
<option value="1">Berherak</option>
<option value="2">Vasberan</option>
</select>
</div>

Unfortunately nothing happens when I change the contents of the species combobox (I've tried on multiple browsers) What am I doing wrong? I realise that getElementsByClassName() is a HTML5 function, but according to the interwebs it is compatible with all major browsers. Thanks for your time

Upvotes: 0

Views: 236

Answers (1)

Denys S&#233;guret
Denys S&#233;guret

Reputation: 382170

getElementsByClassName returns an array, you must iterate on the result. And be careful to the = in tests (instead of ==).

But I suggest you have a look at jquery. Your life will be easier as what you want can be done as :

$('.human, .orc, .elf, .dwarf, .drow, .ent').hide();
$('.'+opt).show();

(see fiddle : http://jsfiddle.net/dystroy/2GmZ3/)

Upvotes: 1

Related Questions