简体   繁体   中英

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.

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

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

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

我正在寻找比我更好的解决方案:

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

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

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>

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM