How can I check whether a option already exist in

2020-01-27 09:56发布

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
7条回答
家丑人穷心不美
2楼-- · 2020-01-27 10:40

Does not work, you have to do this:

if ( $("#your_select_id option[value='enter_value_here']").length == 0 ){
  alert("option doesn't exist!");
}
查看更多
Animai°情兽
3楼-- · 2020-01-27 10:47

This evaluates to true if it already exists:

$("#yourSelect option[value='yourValue']").length > 0;
查看更多
男人必须洒脱
4楼-- · 2020-01-27 10:47

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);
}
查看更多
叼着烟拽天下
5楼-- · 2020-01-27 10:50
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.

查看更多
Juvenile、少年°
6楼-- · 2020-01-27 10:52

Another way using jQuery:

var exists = false; 
$('#yourSelect  option').each(function(){
  if (this.value == yourValue) {
    exists = true;
  }
});
查看更多
【Aperson】
7楼-- · 2020-01-27 10:52
if ( $("#your_select_id option[value=<enter_value_here>]").length == 0 ){
  alert("option doesn't exist!");
}
查看更多
登录 后发表回答