skip to Main Content

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


  1. 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"
    
    Login or Signup to reply.
  2. 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.

    const cities = ["a", "b", "c"];
    const selectCity = document.getElementById("city");
    const output = document.getElementById("output");
    
    cities.forEach(city => selectCity.add(new Option(city, city)));
    
    selectCity.addEventListener("change", () => {
      const selectedCity = selectCity.value;
      output.innerHTML = selectedCity;
      output.style.display = cities.includes(selectedCity) && selectedCity !== "b" ? "block" : "none";
    });
    #output {
        display: none;
    }
    <select name="city" id="city">
        <option value="-">- Choose city -</option>
    </select>
    
    <span id="output"></span>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search