Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

jquery

This evaluates to true if it already exists:

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

Another way using jQuery:

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

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

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){
    ...
}

Does not work, you have to do this:

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