Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 296
Bill Software Engineer Avatar asked Mar 20 '12 16:03

Bill Software Engineer


People also ask

How to check if option exists in select javascript?

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.

How can check select option selected or not in jQuery?

$('#mySelectBox option'). each(function() { if ($(this). isChecked()) alert('this option is selected'); else alert('this is not'); });

Is a jQuery element?

jQuery selectors allow you to select and manipulate HTML element(s). jQuery selectors are used to "find" (or select) HTML elements based on their name, id, classes, types, attributes, values of attributes and much more. It's based on the existing CSS Selectors, and in addition, it has some own custom selectors.


2 Answers

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");
    }
}
like image 85
mas-designs Avatar answered Oct 10 '22 23:10

mas-designs


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 ) ) {
like image 36
Andy Mercer Avatar answered Oct 10 '22 23:10

Andy Mercer