2017-02-27 102 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>