簡體   English   中英

根據輸入值在下拉菜單中添加和刪除選項

[英]Add and Delete the options in the dropdown based on the input values

如果我在輸入框中輸入一個值,然后單擊按鈕。 我想檢查下拉列表中的輸入值(如果下拉列表中存在值)我想刪除該選項,否則我想在選項中添加輸入值。

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;

    }

這應該為您做到這一點。

除其他外,要刪除選項值,請使用select.options.remove(index)並添加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> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM