如何通过 JQuery 检查选​​择中是否已存在选项

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/646317/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 09:30:45  来源:igfitidea点击:

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

jquery

提问by Billy

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

如何通过 JQuery 检查选​​择中是否已存在选项?

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

我想动态地将选项添加到 select 中,因此我需要检查该选项是否已经存在以防止重复。

回答by Tamas Czinege

This evaluates to true if it already exists:

如果它已经存在,则计算结果为 true:

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

回答by HaMinh Nguyen

Another way using jQuery:

使用 jQuery 的另一种方式:

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

回答by Seb

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

回答by alnorth29

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.

这具有自动为您转义值的优点,这使得文本中的随机引号更容易处理。

回答by mike

Does not work, you have to do this:

不起作用,你必须这样做:

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

回答by Sulung Nugroho

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

回答by codeasaurus

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:

我有一个类似的问题。我没有每次都通过 dom 运行搜索,而是通过选择控件的循环将 jquery 选择元素保存在一个变量中并执行以下操作:

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