I’m currently creating a dropdown from Javascript array. I want to show a span when some options are selected.
For example, I want to show the span when options "a" and "c" are selected, but not "b".
var city = ["a","b","c"];
// Add array to city dropdown
var select_city = document.getElementById("city");
for(var i = 0; i < city.length; i++) {
let opt = city[i];
let el = document.createElement("option");
el.textContent = opt;
el.value = opt;
select_city.appendChild(el);
};
// Display output
var output = document.getElementById("output");
select_city.onchange = function() {
output.style.display = (this.value == city.value && this.value == !"b") ? "block":"none";
};
#output {
display: none;
}
<select name="city" id="city">
<option value="-">- Choose city -</option>
</select>
<span id="output"></span>
My code is currently not working and I don’t know why. I’m new to javascript so hope someone can help me see the problem 🙂
Thanks in advanced!
2
Answers
This comparison logic is a bit broken:
There is no
city.value
becausecity
is an array. You can check if that array includesthis.value
:Additionally,
!"b"
doesn’t make much sense. To check if something is not equal to a value, use the!=
(or!==
) operator:The result is:
I think your comparison logic is not true.
And also,
span
doesn’t have any text, so you can’t see any result if your code works correctly.I add sample code below.