Yongke Bill Yu Yongke Bill Yu - 8 months ago 45
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:


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

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