Using Javascript to show/hide div with select

September 12, 2010 at 13:53:20
Specs: Windows Vista

I need to use javascript to show/hide a series of divs based on a users selection in a drop down menu. Below is the relevant coding that I have thus far. Also, the full code can be found at: Thanks in advance for your help.

<script type="text/javascript">

var selectmenu=document.getElementById("select")

selectmenu.onchange=function toggleLayer(){

var chosenoption=this.options[this.selectedIndex]

if (chosenoption.value="select_all"){
document.getElementById('layer_all').style.visibility = 'visible';

else if(chosenoption.value="select_apologetics"){
document.getElementById('layer_apologetics').style.visibility = 'visible';

else if(chosenoption.value="select_bible_study"){
document.getElementById('layer_bible_study').style.visibility = 'visible';

else if(chosenoption.value="select_blessings"){
document.getElementById('layer_blessings').style.visibility = 'visible';
else {
document.write("No resources matched your search criteria.
Please try a different search.");

<form action="" method="post">

Filter Resources by Subject:</p>

<select name="select" id="select" onchange="function toggleLayers();">
<option value="select_all" >All Subjects</option>
<option value="select_apologetics">Apologetics</option>
<option value="select_bible_study">Bible Study</option>
<option value="select_blessings">Blessings</option>

<div id="layer_all">

<div id="layer_apologetics">

<div id="layer_bible_study">
bible study</div>

<div id="layer_blessings">

See More: Using Javascript to show/hide div with select

Report •

September 16, 2010 at 14:40:40
There's a poster here who uses jquery for stuff like this, so maybe he/she will chime in. I don't use jquery, but will try to offer something that will hopefully help you out.

I tend to use stuff like

function toggleLayer(choice){

   var d = document.getElementsByTagName("div");
   var i;
   for(i=0; i < d.length; i++) { d[i].style.visibility = "hidden"; }
   // hide everything

   switch(choice) {
      case 'select_all' : for(i=0; i < d.length; i++) {
                             d[i].style.visibility = "visible";
                          } break;

      default : d[choice == 'select_apologetics' ? 1 :
                  choice == 'select_bible_study' ? 2 : 3].style.visibility = "visible";

<select name="select" id="select" onchange="toggleLayer(this.value);">

I didn't change anything else in what you posted. If all you have is a few divs, then something like the above may do; however, if you've got a lot of them scattered about for different uses, then you'll need to target them specifically.

document.getElementsByTagName("div")['layer_apologetics'].style.visibility = ?
or just
document.getElementById('layer_apologetics').style.visibility = ?


I have no aspiration for preaching. ;-)

Report •
Related Solutions

Ask Question