让一个选择元素影响另一个元素

时间:2013-05-20 15:35:21

标签: javascript html

我最近发布了一个相关问题copying selected option to another select

我意识到我正在努力做的事情更直截了当但我希望我不会通过“双重发布”打破论坛规则,因为这个问题略有不同。开始。我希望“productchoice”影响“productchoice2”。

 <select id="productchoice">
   <option value="1">Option #1</option>
   <option value="2">Option #2</option>
  </select>

  <select id="productchoice2">
   <option value="1">Option #1</option>
   <option value="2">Option #2</option>
  </select>

我的问题是:当“productchoice”发生变化时,我应该使用什么javascript来使“productchoice2”反映出同样的选择?

再次感谢您的帮助,善良的人!

4 个答案:

答案 0 :(得分:2)

<强> HTML

<select id="productchoice" onchange="productchoicechange()">
    <option value="1">Option #1</option>
    <option value="2">Option #2</option>
</select>
<select id="productchoice2">
    <option value="1">Option #1</option>
    <option value="2">Option #2</option>
</select>

<强> JS

jsfiddle by index

// by index
function productchoicechange(){
    var productchoice = document.getElementById("productchoice");
    var productchoice2 = document.getElementById("productchoice2");
    productchoice2.options[productchoice.options.selectedIndex].selected = true;
}

jsfiddle by value

// by value
function productchoicechange(){
    var productchoice = document.getElementById("productchoice");
    var productchoice2 = document.getElementById("productchoice2");
    productchoice2.value = productchoice.value;
}

答案 1 :(得分:1)

如果您想使用jQuery

   $('#productchoice').change(function (){

        $('#productchoice2').val($(this).val());

   });

JSFiddle

答案 2 :(得分:1)

使用纯JS,你可以这样做:

var select_element = document.getElementById('productchoice');

select_element.onchange = function(e){
    document.getElementById('productchoice2').value = this.options[this.selectedIndex].value;
}

演示:http://jsfiddle.net/tymeJV/Zayq4/

答案 3 :(得分:0)

尝试使用angularJS

<强>的jsfiddle: - http://jsfiddle.net/adiioo7/xUPZv/

<强> HTML: -

<html ng-app>     
    <body>
        <select id="productchoice"  ng-model="selection">
            <option value="1">Option #1</option>
            <option value="2">Option #2</option>
        </select>
        <select id="productchoice2" ng-model="selection">
            <option value="1">Option #1</option>
            <option value="2">Option #2</option>
        </select>
    </body>
</html>