我该如何使用 JQuery 检查选项是否已在 select 中存在?
我想在选择框中动态添加选项,因此需要检查选项是否已存在,以防止重复。
我该如何使用 JQuery 检查选项是否已在 select 中存在?
我想在选择框中动态添加选项,因此需要检查选项是否已存在,以防止重复。
如果它已经存在,则为真:
$("#yourSelect option[value= yourValue ]").length > 0;
另一种使用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;
这样做的好处是自动为您转义值,使文本中的随机引用更容易处理。
虽然大多数其他答案对我有用,但我使用了.find()。
if ($("#yourSelect").find( option[value="value"] ).length === 0){
...
}
不起作用,你必须这么做:
if ( $("#your_select_id option[value= enter_value_here ]").length == 0 ){
alert("option doesn t exist!");
}
它帮助了我。
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");
}
});
我有一个类似的问题。但我并不是每次都通过dom来运行搜索,我是将jquery选择元素保存在变量中,并进行了如下操作:
function isValueInSelect($select, data_value){
return $($select).children( option ).map(function(index, opt){
return opt.value;
}).get().includes(data_value);
}