Bill Software Engineer
Bill Software Engineer

Reputation: 7782

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.

Upvotes: 24

Views: 47408

Answers (9)

Andrew Elans
Andrew Elans

Reputation: 83

Add id to select and values to options:

<select id="mySelect">
    <option value="Value">Volvo</option>
    <option value="Saab">Saab</option>
    <option value="Mercedes">Mercedes</option>
    <option value="Audi">Audi</option>
</select>

Then:

document.getElementById("mySelect").querySelector("option[value='Hyndai']") // returns null
document.getElementById("mySelect").querySelector("option[value='Saab']") // returns element as object
!!document.getElementById("mySelect").querySelector("option[value='Hyndai']") // returns false
!!document.getElementById("mySelect").querySelector("option[value='Saab']") // returns true

Upvotes: 3

Paanik
Paanik

Reputation: 21

Wouldn't it be easier to just use the selectedIndex attribute:

function checkExists(optionValue) {
  const sel = document.getElementById("sel");
  // save value
  const val = sel.value;
  // check existence
  sel.value = optionValue;
  const exists = (sel.selectedIndex >= 0);
  // reset value
  sel.value = val;
  return exists;
}

document.addEventListener("DOMContentLoaded", (event) => {
  for (const optionValue of ["Mercedes", "Hyundai"]) {
    const div = document.getElementById(optionValue);
    if (checkExists(optionValue)) {
      div.textContent += " exists";
    } else {
      div.textContent += " does not exist";
    }
  }
});
<select id="sel">
  <option>Volvo</option>
  <option>Saab</option>
  <option>Mercedes</option>
  <option>Audi</option>
</select>
<div id="Mercedes">Mercedes</div>
<div id="Hyundai">Hyundai</div>

Upvotes: 1

Alrik Zachert
Alrik Zachert

Reputation: 29

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

Upvotes: 1

Nathan Arthur
Nathan Arthur

Reputation: 9096

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

Upvotes: 4

pmiguelpinto90
pmiguelpinto90

Reputation: 613

I was searching for a better solution than mine:

[...document.querySelector("select").options].map(o => o.value).includes("Hyndai")

Upvotes: 4

WindsorAndy
WindsorAndy

Reputation: 247

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>

Upvotes: 2

Kelderic
Kelderic

Reputation: 6687

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 ) ) {

Upvotes: 10

Ben
Ben

Reputation: 659

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

Upvotes: 5

mas-designs
mas-designs

Reputation: 7536

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

Upvotes: 27

Related Questions