javascripthtmljquerycss

Change style for element when dropdown is selected with conditions


I'm creating a dropdown from a 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>

Why is this not working? How can I do it correctly?


Solution

  • This comparison logic is a bit broken:

    this.value == city.value && this.value == !"b"
    

    There is no city.value because city is an array. You can check if that array includes this.value:

    city.includes(this.value)
    

    Additionally, !"b" doesn't make much sense. To check if something is not equal to a value, use the != (or !==) operator:

    this.value != "b"
    

    The result is:

    city.includes(this.value) && this.value != "b"