I'm trying to show one div and hide other divs when the selected element holds the corresponding value.
I created a selection element with 4 options, the default value is empty, and the other three options are: down, up, and up. I've placed three hidden div elements below that contain content for each of the 3 options: bottom, top, and top. I want to show and hide each div based on the value of the selected element. This 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>
eventListener
to hide and show elements based on selection, and remove or addd-none
classes as needed.if/else
statement is also wrong,=
is for assignment and==
is for comparison. You can also useswitch case
like my example.You need to wrap it in an event listener and hide all elements before showing them:
This way, whenever the user selects an option, the corresponding
div
will be displayed, while the rest will be hidden.Also, you need to replace every
=
in the if statement with==
because=
in javascript is an assignment, so if you If the assigned value is true, the if statement will run. You're probably looking for==
, the equality comparison operator.Full clip: