I was trying to display a div and hide other div when the select element hold the corresponding value.
I created a select element with 4 options, the default with empty value plus three others, lower, upper, higher. I placed three hidden div elements below containing the content for each of the 3 options: lower, upper and higher. I wanted to show and hide each div based on the values of the select element. Here is my code:
const departments = document.querySelector("#departments");
const lowerdep = document.querySelector(".lower-dep");
const upperdep = document.querySelector(".upper-dep");
const higherdep = document.querySelector(".higher-dep");
if (departments.value = "") {
lowerdep.style.display = "none";
upperdep.style.display = "none";
higherdep.style.display = "none";
} else if (departments.value = "lower") {
lowerdep.style.display = "block";
} else if (departments.value = "upper") {
upperdep.style.display = "block";
} else {
higherdep.style.display = "block";
}
.lower-dep,
.upper-dep,
.higher-dep {
display: none;
}
<div class="">
<div class="">
<label class="">Department
<select id="departments" name="departments">
<option value="" selected>Select Department...</option>
<option value="lower">Lower</option>
<option value="upper">Upper</option>
<option value="higher">Higher</option>
</select>
</label>
</div>
</div>
<div class="lower-dep">
<div class="input-check">
<input type="checkbox" id="color1" name="color1" value="Red">
<label for="color1"> Red</label>
</div>
</div>
<div class="upper-dep">
<div class="input-check">
<input type="checkbox" id="color1" name="color1" value="Red">
<label for="color1"> Red</label>
</div>
</div>
<div class="higher-dep">
<div class="input-check">
<input type="checkbox" id="color1" name="color1" value="Red">
<label for="color1"> Red</label>
</div>
</div>
2
Answers
You’ll want to wrap that in an event listener, and hide all of the elements before showing:
This way whenever the user picks an option the corresponding
div
will be shown, and the rest will be hidden.Also, you will want to replace each
=
with==
in the if statements, as=
in javascript is assignment, so the if statement will run if the value you assign is truthy. You were probably looking for==
, the equality comparison operator instead.Full snippet:
eventListener
to hide and show elements based on selection and just remove or add thed-none
class as needed.if/else
statements were also wrong=
is for assignment and==
for comparisons. You can also useswitch case
like in my example.