tags:

views:

67

answers:

3

Using jQuery, what is the best way to determine if an OPTION element with a particular value or text value exists inside a SELECT element? I've seen all kinds of tips, blogs and howtos on how to find the selected item, but I want to find any item by value or by text value, regardless of whether or not it is selected.

e.g. Given the mark-up below, using jQuery, how do I determine if New Order is in the list?

<select id="music-groups">
  <option value="001">Depeche Mode</option>
  <option value="002">New Order</option>
  <option value="021">AC-DC</option>
  <option value="023">The Who</option>
  <option value="090">The Beatles</option>
  <option value="090">Bjork</option>
</select>
+4  A: 
$('#music-groups option[text=New Order]').length != 0
sje397
I don't get this. OPTION elements do not have the `text` attribute set.
Šime Vidas
@ime - It's not *just* an attribute selector, it checks `element["text"]` as well, and it is a property.
Nick Craver
+1, and a side note: this will work for elements that expose the inner text node's value via the `text` property only.
Andy E
I don't understand why this is getting up-voted. It doesn't do what the question asked.
patrick dw
That worked perfect, thanks! And damn!, all of you are quick!
eponymous23
@eponymous23 - So you *didn't* want to test against the `value` property as well?
patrick dw
Sorry, I stand corrected ... option[text='xxxx'] *didn't* work, @patrick dw is correct. But option[value='xxxx'] will work when searching for the known value, i.e. "002".
eponymous23
@Andy What elements do that?
Šime Vidas
@ime: not many. Pretty much just option elements (with the exception of some other non-scoped elements and nodes in IE).
Andy E
@eponymous23 - you have to put the text there *without* quotes.
sje397
A: 
var findOption = function(selector, value, text) {
   $(selector).each(function(){ 
       if(this.val() == value || this.text() == text) return this;
   });
}
findOption("#music-groups option", "001", "Depeche Mode");

This will match first option having correct value and text

infinity
patrick dw
Well that takes care of points 1 and 4. The trouble with `.val()` and `text()` is that `this` is a DOM element, and as such, doesn't have those methods. And returning `this` from the `.each()` callback has no effect.
patrick dw
+1  A: 

try this... check the length to greater than 1

$("#music-groups:contains('New Order')").length
Suhumar
This one worked!
eponymous23
@eponymous23: be careful with this one. As I explained in my (now deleted) answer, `:contains()` will search for the text anywhere. In this example, an option containing "Place A New Order" would also be returned.
Andy E