eponymous23
eponymous23

Reputation: 1148

Finding an OPTION element in a SELECT element using jQuery

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>

Upvotes: 0

Views: 262

Answers (3)

sje397
sje397

Reputation: 41822

$('#music-groups option[text="New Order"]').length != 0

Upvotes: 5

Suhumar
Suhumar

Reputation: 405

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

$("#music-groups:contains('New Order')").length

Upvotes: 1

Alex Rashkov
Alex Rashkov

Reputation: 10015

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

Upvotes: 0

Related Questions