20

Given a select

<select id="Myselect">
<option value="-1">Please Select<option>
<option value="1">Selection 1<option>
<option value="2">Selection 2<option>
</select>

What the best way to determine if there is an option of value X in the select with JQuery?

Dan
  • 29,100
  • 43
  • 148
  • 207

2 Answers2

37

You can do this using a selector and .length, like this:

var exists = $("#mySelect option[value='-1']").length !== 0;

Or as a function:

function optionExists(val) {
  return $("#mySelect option[value='" + val + "']").length !== 0;
}

If it's not numbers and you may have ' in there for example (screwing the selector), you can use .filter(), like this:

function optionExists(val) {
  return $("#mySelect option").filter(function() {
           return this.value === val;
         }).length !== 0;
}
Nick Craver
  • 623,446
  • 136
  • 1,297
  • 1,155
  • 1
    why not using `var exists = $("#mySelect option[value='-1']") != undefined`, getting the objects to access directly – jAndy Jun 30 '10 at 12:14
  • @jAndy - Because it's not undefined :) It's a jQuery object containing 0 DOM elements, so `.length === 0` :) Here's an example: http://jsfiddle.net/2drxN/ – Nick Craver Jun 30 '10 at 12:15
  • @jAndy - You're trying to access the first element in an array that has no elements so yes *that* will be undefined :) The normal `$("anything")` will never be undefined though, it'll just have no elements to execute the rest of the chain on. – Nick Craver Jun 30 '10 at 12:30
  • @Nick: I'm not sure if `var exists = $("#mySelect option[value='-1']")[0]` would bring any benefit. If something is found, you'll have the DOMelement in `exists` fine, but you still would have to wrap it into a jQuery object afterwards. So maybe a stupid approach :) – jAndy Jun 30 '10 at 12:35
6

The :has() selector should work, something like this:

var exists = $("#Myselect:has(option[value='X'])").length > 0;

This is far from the only way, but an easy to understand approach. You could also do somethi.g like this for an .Exists() function since .length > 0 is sometimes not clear to mean it does exist.

Community
  • 1
  • 1
naspinski
  • 34,020
  • 36
  • 111
  • 167
  • `.length > 0` means the selector *found* something, meaning it exists ..so can you explain your last statement? I'm not following there. Also you need a closing `]` in there...but I wouldn't go this way, this is just extra work inside Sizzle. – Nick Craver Jun 30 '10 at 12:21