Yongke Bill Yu Yongke Bill Yu - 5 months ago 26
Javascript Question

Check if an option exist in select element without JQuery?

Unfortunately I don't have access to JQuery and all it's nicety. But I do have access to JavaScript. How do I check if an OPTION exist in a HTML Select?

EDIT: To clarify, I need to know if an option exist. So for example:

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


I check if "Hyndai" is an OPTION, and it is not.

Answer
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");
    }
}