如果我在输入框中输入一个值并单击按钮。我想检查下拉列表中的输入值(如果下拉列表中存在这些值)我想删除该选项,否则我想在选项中添加输入值。
HTML:
<input type="text" id="inputValue" />
<button id="myBtn" onclick="validate()">Click</button>
<select id="mySelect">
<option>Apple</option>
<option>Orange</option>
<option>Mango</option>
<option>Lemon</option>
</select>
JS:
function validate() {
var ipValue = document.getElementById('inputValue').value;
var select = document.getElementById('mySelect');
for(i=0;i<select.length;i++) {
if(select[i] == ipValue) {
ipValue.removeChild(select[i]);
}
else {
var option = document.createElement('option');
select.appendChild(option);
option.innerHTML = ipValue;
}
}
}
最佳答案
function validate() {
var ipValue = document.getElementById('inputValue').value;
var select = document.getElementById("mySelect");
var selectOption = select.children;
for (i = 0; i < select.length; i++) {
if (selectOption[i].text == ipValue) {
select.removeChild(selectOption[i]);
return;
}
}
var option = document.createElement('option');
select.appendChild(option);
option.text = ipValue;
}
关于javascript - 根据输入值添加和删除下拉列表中的选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35802838/