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

时间:2009-03-14 17:32:17

标签: jquery

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

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

8 个答案:

答案 0 :(得分:297)

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

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

答案 1 :(得分:19)

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

答案 2 :(得分:18)

使用jQuery的另一种方式:

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

答案 3 :(得分:14)

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

这样做的好处是可以为你自动转义值,这使得文本中的随机引号更容易处理。

答案 4 :(得分:2)

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

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

答案 5 :(得分:1)

尽管大多数其他答案对我都有效,但我还是使用了.find():

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

答案 6 :(得分:0)

这对我很有帮助:

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

答案 7 :(得分:0)

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

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