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>
4

3 回答 3

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/

于 2013-07-26T14:11:45.727 回答
0

如果两个选择标签具有相同的选项:

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

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

小提琴

请注意,对于具有不同选项的选择,这个简单的解决方案将是错误的。在这种情况下,这将起作用:

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;
    }
});

更新的小提琴

于 2013-07-26T14:08:28.323 回答
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>

于 2013-07-26T14:12:48.820 回答