javascripthtml

How can I check if a specific option exists in a select box?


I have the HTML code below:

<select>
 <option>Volvo</option>
 <option>Saab</option>
 <option>Mercedes</option>
 <option>Audi</option>
</select>

How can I check whether or not the text 'Hyndai' is in the list of options.


Solution

  • document.getElementById("myselect").options[0] //accesses first option via options[]
    

    would select the first option in your select. If it fails you know that there are no options in your select. If you get data by appending .value after the .options[0] it's not empty. Without javascript you will not be able to achieve this. Only HTML does not deliver the functionality you want.

    for (i = 0; i < document.getElementById("myselect").length; ++i){
        if (document.getElementById("myselect").options[i].value == "Hyndai"){
          alert("Hyndai is available");
        }
    }