21

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.

graphicdivine
  • 10,937
  • 7
  • 33
  • 59
Bill Software Engineer
  • 7,362
  • 23
  • 91
  • 174
  • 1
    You want to check if a *particular* `option` exists, or just check that there is *at least one* `option` in the `select` element? And, incidentally, you'll need to use JavaScript for this. – David Thomas Mar 20 '12 at 16:39

7 Answers7

26
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");
    }
}
mas-designs
  • 7,498
  • 1
  • 31
  • 56
9

I ran into this issue today and used these answers to come up with my own, which I think is a little easier to use.

I loop through the select's options (caching the length), but I put that loop into the HTMLSelectElement itself through it's prototype, as a .contains() function.

HTMLSelectElement.prototype.contains = function( value ) {

    for ( var i = 0, l = this.options.length; i < l; i++ ) {

        if ( this.options[i].value == value ) {

            return true;

        }

    }

    return false;

}

Then to use it, I simply write this:

if ( select.contains( value ) ) {
Kelderic
  • 6,502
  • 8
  • 46
  • 85
5

I understand there is already a chosen answer but for other people getting here from searching, I believe the accepted answer can be improved, by for example caching the selection of 'myselect'.

I think wrapping the logic in a reusable function and passing it the option you are looking for and the object would make sense:

/**
 * Return if a particular option exists in a <select> object
 * @param {String} needle A string representing the option you are looking for
 * @param {Object} haystack A Select object
*/
function optionExists ( needle, haystack )
{
    var optionExists = false,
        optionsLength = haystack.length;

    while ( optionsLength-- )
    {
        if ( haystack.options[ optionsLength ].value === needle )
        {
            optionExists = true;
            break;
        }
    }
    return optionExists;
}

Usage:

optionExists( 'searchedOption', document.getElementById( 'myselect' ) );
Ben
  • 579
  • 6
  • 7
4

I was searching for a better solution than mine:

[...document.querySelector("select").options].map(o => o.value).includes("Hyndai")
Nathan Arthur
  • 8,287
  • 7
  • 55
  • 80
pmiguelpinto90
  • 573
  • 9
  • 19
2

Check for value attribute

Use the value property on the HTMLOptionElement object to check if there is an option with the specified value attribute. Note that an option's value will fall back to its text content if no such attribute is provided.

const select = document.querySelector("select");
const optionLabels = Array.from(select.options).map((opt) => opt.value);
const hasOption = optionLabels.includes("Hyndai");

Based on Miguel Pynto's answer

Check for <option> display text

To instead check whether an option exists with specified display text, regardless of its value attribute, use the text property on the HTMLOptionElement object. The only difference between these two snippets is the end of the second line.

const select = document.querySelector("select");
const optionLabels = Array.from(select.options).map((opt) => opt.text);
const hasOption = optionLabels.includes("Hyndai");

Based on this answer

Nathan Arthur
  • 8,287
  • 7
  • 55
  • 80
1

Another possibility would be to utilize Array.prototype.find:

  /**
   * @param {HTMLSelectElement} selectElement
   * @param {string} optionValue
   * @return {boolean}
   */
  function optionExists(selectElement, optionValue) {
      return !!Array.prototype.find.call(selectElement.options, function(option) {
          return option.value === optionValue;
      }
  )
1

Because I'm going to add an option to the select if it doesn't currently exist, I simply set the Select's value to the item I want to check exists, then read the element's selectedIndex property. If it's -1, then the option doesn't currently exist in the control.

<select id="mySelect">
 <option>Apple</option>
 <option>Orange</option>
 <option>Pineapple</option>
 <option>Banana</option>
</select>

<script>
function myFunction() {
 document.getElementById("mySelect").value = "Banana";
 alert(document.getElementById("mySelect").selectedIndex);
 //yields 3
 document.getElementById("mySelect").value = "Strawberry";
 alert(document.getElementById("mySelect").selectedIndex);
 //yields -1
}
</script>
WindsorAndy
  • 237
  • 1
  • 11