tags:

views:

31

answers:

2

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?

+3  A: 

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
why not using `var exists = $("#mySelect option[value='-1']") != undefined`, getting the objects to access directly
jAndy
@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
@Nick: doh woh!
jAndy
@Nick: what about http://jsfiddle.net/5sjFb/1/
jAndy
@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
@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
A: 

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.

naspinski
`.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
sorry, fixed that above
naspinski