I have a select box and want to show a help text in a hidden div when you click on an option:
<select onchange="optionCheck()" multiple="multiple" name="test" id="options" size="15" class="form-select">
<option value="1">option 1</option>
<option value="2">option 2</option>
</select>
<div id="help1" style=visibility:hidden>help text 1</div>
<div id="help2" style=visibility:hidden>help text 2</div>
<script type="text/javascript">
function optionCheck(){
var option = document.getElementById("options").value;
if(option == "1"){
document.getElementById("help1").style.visibility ="visible";
document.getElementById("help2").style.visibility ="hidden";
}
if(option == "2"){
document.getElementById("help2").style.visibility ="visible";
document.getElementById("help1").style.visibility ="hidden";
}
}
</script>
How can I create a simple loop so I don’t have to write “if” statements for each option?
document.getElementById(option).style.visibility ="visible";
isn’t working – javascript and me don’t get along well 😉
Also, is there a simple way to hide all other divs when an option is selected?
Here’s how I’d do it:
First, I’m pretty lazy, and I don’t want to type style=”visibility: hidden;” on each of those divs. It’s easier to hide all of them at once with CSS:
HTML:
CSS:
Now we can work on making that Javascript a little more generic:
And that should do the trick!
If you have any questions about the code above, I’d be happy to answer them.