Check if value is in select list with JQuery

user271507 picture user271507 · Feb 12, 2010 · Viewed 162.1k times · Source

How can I, using JQuery, check if a value belongs to dropdown list or not?

Answer

Lachlan Roche picture Lachlan Roche · Feb 12, 2010

Use the Attribute Equals Selector

var thevalue = 'foo';
var exists = 0 != $('#select-box option[value='+thevalue+']').length;

If the option's value was set via Javascript, that will not work. In this case we can do the following:

var exists = false;
$('#select-box option').each(function(){
    if (this.value == 'bar') {
        exists = true;
        return false;
    }
});