Check if value is in select list with JQuery

2019-01-22 05:11发布

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

5条回答
Anthone
2楼-- · 2019-01-22 05:30

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.

查看更多
欢心
3楼-- · 2019-01-22 05:34

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;
    }
});
查看更多
Root(大扎)
4楼-- · 2019-01-22 05:37

if(!$('#select-box').find("option:contains('" + thevalue  + "')").length){
//do stuff
}

查看更多
干净又极端
5楼-- · 2019-01-22 05:38

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;
   }
查看更多
闹够了就滚
6楼-- · 2019-01-22 05:39

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();
查看更多
登录 后发表回答