Justin Brewer
Justin Brewer

Reputation: 13

How can I show/hide divs depending on dropdown selection?

I am just learning javascript and I could use some help. I have found a way to show #divA if one of the first two options are selected but how can I show #divB if the third option is selected? I don't want these divs to show unless the corresponding option is selected in the dropdown menu.

HTML:

<select class="form-control" onchange="showOptionsBelow(this)">
      <option></option>
      <option value="First option">First option</option>
      <option value="Second option">Second option</option>
      <option value="Third option">Third option</option>
</select>

<div id="divA" style="display:none;"></div>
<div id="divB" style="display:none;"></div>

Javascript:

<script>
function showOptionsBelow(elem) {
    if (elem.value == "First Option" || elem.value == "Second Option") {
      document.getElementById("divA").style.display = "block";
    } else {document.getElementById("divA").style.display = "none";
    }
}
</script>

Upvotes: 0

Views: 53

Answers (2)

tiborK
tiborK

Reputation: 385

You are passing the whole select element into the showOptionsBelow function. Try this:

console.log(elem.options[elem.selectedIndex].value)

Upvotes: -1

cнŝdk
cнŝdk

Reputation: 32145

Well you just need to hide the second div when you show the first and show the second one when you hide the first, do the same with the second div:

  if (elem.value == "First option" || elem.value == "Second option") {
    document.getElementById("divA").style.display = "block";
    document.getElementById("divB").style.display = "none";
  } else {
    document.getElementById("divB").style.display = "block";
    document.getElementById("divA").style.display = "none";
  }
}

Note:

Make sure you use the correct "First option" and "Second option" from the options values in your if condition, otherwise your condition will be always false and you will fall always in the else statement.

Demo:

function showOptionsBelow(elem) {
  if (elem.value == "First option" || elem.value == "Second option") {
    document.getElementById("divA").style.display = "block";
    document.getElementById("divB").style.display = "none";
  } else {
    document.getElementById("divB").style.display = "block";
    document.getElementById("divA").style.display = "none";
  }
}
<select class="form-control" onchange="showOptionsBelow(this)">
      <option></option>
      <option value="First option">First option</option>
      <option value="Second option">Second option</option>
      <option value="Third option">Third option</option>
</select>

<div id="divA" style="display:none;">A</div>
<div id="divB" style="display:none;">B</div>

Upvotes: 2

Related Questions