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

Jquery

Jquery Problem Overview


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.

Jquery Solutions


Solution 1 - Jquery

This evaluates to true if it already exists:

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

Solution 2 - Jquery

Another way using jQuery:

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

Solution 3 - Jquery

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

Solution 4 - Jquery

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.

Solution 5 - Jquery

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

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

Solution 6 - Jquery

Does not work, you have to do this:

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

Solution 7 - Jquery

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");
        				 }
  });

Solution 8 - Jquery

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);
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBillyView Question on Stackoverflow
Solution 1 - JqueryTamas CzinegeView Answer on Stackoverflow
Solution 2 - JqueryHaMinh NguyenView Answer on Stackoverflow
Solution 3 - JquerySebView Answer on Stackoverflow
Solution 4 - Jqueryalnorth29View Answer on Stackoverflow
Solution 5 - JqueryStrabekView Answer on Stackoverflow
Solution 6 - JquerymikeView Answer on Stackoverflow
Solution 7 - JquerySulung NugrohoView Answer on Stackoverflow
Solution 8 - JquerycodeasaurusView Answer on Stackoverflow