'Check if select contains a specific value
I have a select with about 50 items, here's a small sample. I want to check if the select contains a specific exact value, so when looking for 'Beauty', that would be 1 match and not 2.
I thought of looping through all items, but then I came across this: http://api.jquery.com/is/
and thought that might perform better. I however, have no idea how to use it on this code:
<select id="mydropdown" class="textbox">
<option value="Beauty">Beauty</option>
<option value="Catering">Catering</option>
<option value="Beautysalon">Beautysalon</option>
</select>
Solution 1:[1]
Use an attribute selector:
var hasBeauty = !! $('#mydropdown > option[value="Beauty"]').length;
Here's the fiddle: http://jsfiddle.net/gLPJ5/
Solution 2:[2]
if($('#mydropdown').val() == "Beauty")
{
//Do something
}
Solution 3:[3]
This is a faster, modern solution that doesn't use querySelector
or jQuery
.
What it does, is it takes the options
object, converts it to an array and uses includes
to check for the value. All methods are part of the native JS api.
function optionExists (select, value) {
const options = Object.values(select.options).map(option => option.value)
return options.includes(value)
}
const select = document.getElementById('mydropdown')
console.log(optionExists(select, 'Beauty'))
console.log(optionExists(select, 'Be'))
<select id="mydropdown" class="textbox">
<option value="Beauty">Beauty</option>
<option value="Catering">Catering</option>
<option value="Beautysalon">Beautysalon</option>
</select>
Solution 4:[4]
ES6 / vanilla :
(select, optionValue) => [...select.options].some((o) => o.value == optionValue);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | Venkata Krishna |
Solution 3 | |
Solution 4 | noontz |