使用JQuery检查值是否在选择列表中
问题描述:
如何使用JQuery检查一个值是否属于下拉列表?
How can I, using JQuery, check if a value belongs to dropdown list or not?
答
使用属性等价选择器
var thevalue = 'foo';
var exists = 0 != $('#select-box option[value='+thevalue+']').length;
如果该选项的值是通过Javascript设置的,那将不起作用。在这种情况下,我们可以执行以下操作:
If the option's value was set via Javascript, that will not work. In this case we can do the following:
var exists = false;
$('#select-box option').each(function(){
if (this.value == 'bar') {
exists = true;
return false;
}
});