Check if an option exist in select element without JQuery?
I was searching for a better solution than mine:
[...document.querySelector("select").options].map(o => o.value).includes("Hyndai")
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' ) );