我正在尝试添加和删除基于其他字段的选择选项。在这个网站上有很多关于添加和删除选项的答案,但我只需添加该选项(如果它尚不存在)。到目前为止,我有:
function setCustomerOptions() {
var customers = getField('select', 'Customer');
if (getField('select', 'Campaign Type').value == 'Game' || getField('select', 'Campaign Type').value == 'Innovation') {
for (var i=0; i<customers.length; i++) {
if (customers.options[i].text == 'N/A') {
customers.remove(i);
}
}
} else {
if ($.inArray('N/A', customers.options.text) == -1) {
var opt = document.createElement('option');
opt.value = 'N/A';
opt.innerHTML = 'N/A';
customers.appendChild(opt);
}
}
}
这成功添加并删除了'N / A'选项,但是如果我选择除初始条件以外的任何内容,我会继续添加额外的'N / A'。我认为Aquray中的Jquery可能有所帮助,但没有。
如何找到当前不存在选择选项?
答案 0 :(得分:0)
试试这个..
<form>
<select id="mySelect" size="8">
<option>Apple</option>
<option>Pear</option>
<option>Banana</option>
<option>Orange</option>
</select>
</form>
<br>
<button type="button" onclick="myFunction()">Insert option</button>
<button onclick="myremove()">Remove</button>
<script>
function myFunction() {
var x = document.getElementById("mySelect");
var option = document.createElement("option");
option.text = "Kiwi";
x.add(option);
}
function myremove() {
var x = document.getElementById("mySelect");
x.remove(x.selectedIndex);
}
</script>
答案 1 :(得分:0)
我无法获得任何jquery选项[感谢找到类似的问题史蒂文]所以最终用普通的javascript做了很长时间:
function setCustomerOptions() {
var customers = getField('select', 'Customer');
if (getField('select', 'Campaign Type').value == 'Game' || getField('select', 'Campaign Type').value == 'Innovation') {
for (var i=0; i<customers.length; i++) {
if (customers.options[i].text == 'N/A') {
customers.remove(i);
}
}
} else {
for (var i=0; i<customers.length; ++i) {
if (customers.options[i].text == "N/A") {
var optexist = 1;
break;
} else {
var optexist = 0;
}
}
if (optexist == 0) {
var opt = document.createElement('option');
opt.value = 'N/A';
opt.innerHTML = 'N/A';
customers.appendChild(opt);
}
}
}