2016-03-04 117 views
2

如果我在輸入框中輸入一個值並單擊按鈕。我想檢查下拉列表中的輸入值,如果這些值存在於下拉列表中,我想刪除該選項,否則我想在選項中添加輸入值。根據輸入值添加和刪除下拉列表中的選項

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

問題是什麼,什麼是您會收到錯誤? –

+0

@pascal betz我無法使用下拉菜單檢查輸入值。我想檢查輸入的值在下拉列表中..如果值exixts刪除選項,否則要添加元素。 –

回答

2

這應該爲你做的。

的措施包括刪除您使用select.options.remove(index)選項值,並添加

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>

+0

工作完美(Y)...感謝:) –

+0

雖然我沒有輸入任何文字的空白點擊按鈕添加到下拉列表。如何避免這種情況。 –

+0

@Raja更新我的答案來解決這個問題。它也修剪空白,所以他們不會被添加以及 – LGSon

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; 

    } 
+0

當然...感謝兄弟:) –

+0

我已經更新了我的答案。請檢查這一個 –

+0

當然我會檢查.. 。 –

相關問題