2013-07-26 27 views
1

我需要你的幫助,在選擇框中進行選擇,並顯示所選擇的答案到另一個

我不確定如何去了解以下信息:

如果我選擇顏色綠成第一個選擇框,我需要將選定的選項自動選入第二個選擇框。

你是如何用javascript來完成這項工作的。

<!DOCTYPE html> 
<html> 
<head> 
</head> 
<body> 
<span>Category:</span> 
<br> 
<select id="select1"> 
    <option value=""></option> 
    <option value="RED">RED</option> 
    <option value="BLUE">BLUE</option> 
    <option value="GREEN">GREEN</option> 
    <option value="YELLOW">YELLOW</option> 
</select> 
<br> 
<span>Your selection was:</span> 
<br> 
<select id="select2"> 
    <option value=""></option> 
    <option value="RED">RED</option> 
    <option value="BLUE">BLUE/option> 
    <option value="GREEN">GREEN</option> 
    <option value="YELLOW">YELLOW</option> 
</select><b></b> 
</body> 
</html> 
+0

不要告訴我你沒有試過任何東西.... –

回答

0

如果兩個選擇標記具有相同的選項:

var select1 = document.getElementById('select1'); 
var select2 = document.getElementById('select2'); 

select1.addEventListener('change', function(){ 
    select2.selectedIndex = this.selectedIndex; 
}); 

Fiddle

注意這個簡單的解決方案將是錯誤的,有不同的選項中選擇。在這種情況下,這將工作:

select1.addEventListener('change', function(){ 
    for(var i = 0; i < select2.options.length; i++){ 
     if(select2.options[i].value === this.options[this.selectedIndex].value) 
      select2.options[i].selected = true; 
    } 
}); 

Updated fiddle

+0

我將使用的選擇確實有2個不同的選項。那麼代碼是什麼?看起來你已經知道了! –

+0

@JohnSmith查看更新後的答案 – karaxuna

1

您可以通過選項進行迭代,直到找到相同的值:

document.getElementById("select1").onchange = function() { 
    var selected = this.value; 
    var select2 = document.getElementById("select2"); 

    //find the index in the second select 
    for (var i = 0; i < select2.options.length; i++) { 
     if (select2.options[i].value == selected) { 
      select2.options[i].selected = true; 
     } 
    } 
} 

演示:http://jsfiddle.net/HJm7E/

0
<!DOCTYPE html> 
<html> 
<head> 
    <script> 
     function doOnload() { 
      var slt1 = document.getElementById("select1"); 
      var slt2 = document.getElementById("select2"); 
      slt1.onchange = function() { 
       slt2.options[slt1.selectedIndex].selected = true; 
      }; 
     } 
    </script> 
</head> 
<body onload="doOnload()"> 
    <span>Category:</span> 
    <br> 
    <select id="select1"> 
     <option value=""></option> 
     <option value="RED">RED</option> 
     <option value="BLUE">GREEN</option> 
     <option value="GREEN">GREEN</option> 
     <option value="YELLOW">YELLOW</option> 
    </select> 
    <br> 
    <span>Your selection was:</span> 
    <br> 
    <select id="select2"> 
     <option value=""></option> 
     <option value="RED">RED</option> 
     <option value="BLUE">GREEN</option> 
     <option value="GREEN">GREEN</option> 
     <option value="YELLOW">YELLOW</option> 
    </select><b></b> 
</body> 

相關問題