[jquery] How can I check whether a option already exist in select by JQuery

How can I check whether a option already exist in select by JQuery?

I want to dynamically add options into select and so I need to check whether the option is already exist to prevent duplication.

This question is related to jquery

The answer is


This evaluates to true if it already exists:

$("#yourSelect option[value='yourValue']").length > 0;

Does not work, you have to do this:

if ( $("#your_select_id option[value='enter_value_here']").length == 0 ){
  alert("option doesn't exist!");
}

I had a similar issue. Rather than run the search through the dom every time though the loop for the select control I saved the jquery select element in a variable and did this:

function isValueInSelect($select, data_value){
    return $($select).children('option').map(function(index, opt){
        return opt.value;
    }).get().includes(data_value);
}

var exists = $("#yourSelect option")
               .filter(function (i, o) { return o.value === yourValue; })
               .length > 0;

This has the advantage of automatically escaping the value for you, which makes random quotes in the text much easier to deal with.


Although most of other answers worked for me I used .find():

if ($("#yourSelect").find('option[value="value"]').length === 0){
    ...
}

Another way using jQuery:

var exists = false; 
$('#yourSelect  option').each(function(){
  if (this.value == yourValue) {
    exists = true;
  }
});

It's help me :

  var key = 'Hallo';

   if ( $("#chosen_b option[value='"+key+"']").length == 0 ){
   alert("option not exist!");

    $('#chosen_b').append("<option value='"+key+"'>"+key+"</option>");
    $('#chosen_b').val(key);
   $('#chosen_b').trigger("chosen:updated");
                         }
  });

if ( $("#your_select_id option[value=<enter_value_here>]").length == 0 ){
  alert("option doesn't exist!");
}