bra*_*ter 3 jquery html-select
我有一堆独特的选择<select>.我需要添加一个新选项,只有它是唯一的并且不存在于现有选项中.
如何使用jquery 查找给定的option已存在select?
例如:
<select id="combobox">
<option value="">Select one...</option>
<option value="Apple">Apple</option>
<option value="Banana">Banana</option>
<option value="Pears">Pears</option>
</select>
Run Code Online (Sandbox Code Playgroud)
if (!$("#combobox option[value='Apple']").length)
// Add it
Run Code Online (Sandbox Code Playgroud)
使其可重用可以是:
if (!$("#combobox option[value='" + value + "']").length)
// Add it
Run Code Online (Sandbox Code Playgroud)
不区分大小写:
var isExist = !$('#combobox option').filter(function() {
return $(this).attr('value').toLowerCase() === value.toLowerCase();
}).length;?
Run Code Online (Sandbox Code Playgroud)
完整代码:(演示版)
$('#txt').change(function() {
var value = this.value;
var isExist = !!$('#combobox option').filter(function() {
return $(this).attr('value').toLowerCase() === value.toLowerCase();
}).length;
if (!isExist) {
console.log(this.value + ' is a new value!');
$('<option>').val(this.value).text(this.value).appendTo($('#combobox'));
}
});?
Run Code Online (Sandbox Code Playgroud)