2017-02-27 162 views
-2

我有兩個選擇框。如何根據另一個文本框的文本在一個框中顯示/隱藏某些選項?Javascript選擇元素顯示選項

例如,我有兩個Box Job和Year。如果我在工作箱中選擇學生選項,年份框僅顯示選項1年和2年,如果我在工作框中選擇選項講師,年份框會顯示2年和5年選項?

+0

你嘗試過什麼?用你想要實現的代碼的例子來幫助你會更容易。 –

+0

if(document.getElementById(「job」).text ==「Student」){ \t \t \t \t x.remove(0); \t \t \t \t x.remove(0); \t \t \t \t x.add(option1); \t \t \t \t x.add(option2); \t \t \t \t \t \t \t} \t \t \t如果(的document.getElementById( 「工作」)。文本== 「講師」 ||的document.getElementById( 「工作」)。文本== 「其他」){ \t \t \t \t x.remove(0); \t \t \t \t x.remove(0); \t \t \t \t x.add(option2); \t \t \t \t x.add(option3); \t \t \t} –

+0

編輯到您原來的文章,所以你可以得到適當的格式:) –

回答

0

var sel1 = document.querySelector('#sel1'); 
 
    var sel2 = document.querySelector('#sel2'); 
 
    var options2 = sel2.querySelectorAll('option'); 
 

 
    function giveSelection(selValue) { 
 
     sel2.innerHTML = ''; 
 
     for(var i = 0; i < options2.length; i++) { 
 
     if(options2[i].dataset.option === selValue) { 
 
      sel2.appendChild(options2[i]); 
 
     } 
 
     } 
 
    } 
 

 
    giveSelection(sel1.value);
<select id="sel1" onchange="giveSelection(this.value)"> 
 
     <option value="s">student</option> 
 
     <option value="l">lecturer</option> 
 
    </select> 
 
    <select id="sel2"> 
 
     <option data-option="s">1 year</option> 
 
     <option data-option="s">2 years</option> 
 
     <option data-option="l">2 years</option> 
 
     <option data-option="l">5 years</option> 
 
    </select>