Check if value is in select list with JQuery
Here is another similar option. In my case, I'm checking values in another box as I build a select list. I kept running into undefined values when I would compare, so I set my check this way:
if ( $("#select-box option[value='" + thevalue + "']").val() === undefined) { //do stuff }
I've no idea if this approach is more expensive.
Just in case you (or someone else) could be interested in doing it without jQuery:
var exists = false;
for(var i = 0, opts = document.getElementById('select-box').options; i < opts.length; ++i)
if( opts[i].value === 'bar' )
{
exists = true;
break;
}
Why not use a filter?
var thevalue = 'foo';
var exists = $('#select-box option').filter(function(){ return $(this).val() == thevalue; }).length;
Loose comparisons work because exists > 0 is true, exists == 0 is false, so you can just use
if(exists){
// it is in the dropdown
}
Or combine it:
if($('#select-box option').filter(function(){ return $(this).val() == thevalue; }).length){
// found
}
Or where each select dropdown has the select-boxes class this will give you a jquery object of the select(s) which contain the value:
var matched = $('.select-boxes option').filter(function(){ return $(this).val() == thevalue; }).parent();
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;
}
});