128

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

user271507
  • 1,229
  • 2
  • 9
  • 9

8 Answers8

199

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;
    }
});
Lachlan Roche
  • 25,678
  • 5
  • 79
  • 77
  • 8
    The explicit second approach is also safer as it allows option values containing any character, including `]` and `\\`. Avoid building selector strings from raw text without doing proper CSS-escaping. – bobince Feb 12 '10 at 01:28
  • 15
    Return false is used to break/end .each loop. – Angel May 16 '13 at 11:47
  • If you create new options by JavaScript using this logic: $('#select-box').append($('')); (or of course in more talkative style), the first example will work (you don't need to iterate). – Lukas Jelinek Dec 01 '14 at 19:37
  • 1
    I can't seem to find a case where the first code snippet doesn't work. I've tried both appending a new option and setting an existing option's value with jQuery's val() function. In both cases, the first code snippet still worked. In what case would it fail? – dallin Aug 05 '15 at 03:50
  • Just wanted to point out in the first example you are missing the quotes for the value. `option[value"'+thevalue+'"]'` – Charles Driver Jr. Dec 30 '16 at 17:24
18

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;
   }
Marco Demaio
  • 33,578
  • 33
  • 128
  • 159
18

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.

cam_pdx
  • 197
  • 2
  • 8
11

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();
keV
  • 244
  • 3
  • 3
7

if(!$('#select-box').find("option:contains('" + thevalue  + "')").length){
//do stuff
}
Julian
  • 33,915
  • 22
  • 119
  • 174
elaine
  • 117
  • 1
  • 1
1

I know this is kind of an old question by this one works better.

if(!$('.dropdownName[data-dropdown="' + data["item"][i]["name"] + '"] option[value="'+data['item'][i]['id']+'"]')[0]){
  //Doesn't exist, so it isn't a repeat value being added. Go ahead and append.
  $('.dropdownName[data-dropdown="' + data["item"][i]["name"] + '"]').append(option);
}

As you can see in this example, I am searching by unique tags data-dropdown name and the value of the selected option. Of course you don't need these for these to work but I included them so that others could see you can search multi values, etc.

cnnr
  • 1,267
  • 4
  • 18
  • 23
PhanFree
  • 23
  • 4
1
if ($select.find('option[value=' + val + ']').length) {...}
  • 1
    Welcome on SO. Your answer could be improved: by adding a description of your code. Tell us how it works and how it solves the problem. – Krzysztof Madej Dec 09 '20 at 11:44
0

Having html collection of selects you can check if every select has option with specific value and filter those which don't match condition:

//get select collection:
let selects = $('select')
//reduce if select hasn't at least one option with value 1
.filter(function () { return [...this.children].some(el => el.value == 1) });
alanextar
  • 1,094
  • 13
  • 16