Adam
Adam

Reputation: 6122

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>

Upvotes: 2

Views: 3182

Answers (4)

noontz
noontz

Reputation: 1997

ES6 / vanilla :

(select, optionValue) => [...select.options].some((o) => o.value == optionValue);

Upvotes: 0

user670839
user670839

Reputation:

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>

Upvotes: 0

Joseph Silber
Joseph Silber

Reputation: 219920

Use an attribute selector:

var hasBeauty = !! $('#mydropdown > option[value="Beauty"]').length;

Here's the fiddle: http://jsfiddle.net/gLPJ5/

Upvotes: 5

Venkata Krishna
Venkata Krishna

Reputation: 15112

if($('#mydropdown').val() == "Beauty")
{
  //Do something
}

Upvotes: 0

Related Questions