If i enter a value in the input box and click the button. i want to check the input values in the drop down if the values exists in the dropdown i want to remove that option elsei want to add the input value in the option.
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;
}
}
}
答案 0 :(得分:3)
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;
}
答案 1 :(得分:2)
This one should do that for you.
Amongst others, to delete an option value you use select.options.remove(index)
and to add select.add(option)
function validate() {
var ipValue = document.getElementById('inputValue').value;
var select = document.getElementById('mySelect');
for(i=0;i<select.options.length;i++) {
if(select.options[i].text == ipValue) {
select.options.remove(i);
return;
}
}
if(ipValue.trim().length > 0) {
var option = document.createElement('option');
option.text = ipValue;
select.add(option)
}
}
<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>