Javascript - 组合框改变其他组合框的值

RBA*_*RBA 2 javascript combobox javascript-events

我在表格上有2个组合框.每个都有值Yes和No.我想要的是当一个被改变时另一个得到反面(如果第一个是Yes,另一个是No).我需要用javascript来做.我看到了这个问题如何使用JavaScript更改组合框中的"选定"值?但它仅适用于一个组合框.

我怎样才能做到这一点?

LE:我需要这个例子来制作组合框.我不能使用单选按钮

kap*_*apa 6

我创建了一个简单的jsFiddle演示.这并不完美,只是说明了这个想法.

HTML:

<select id="first">
    <option value="0" selected>No</option>
    <option value="1">Yes</option>
</select>

<select id="second">
    <option value="0">No</option>
    <option value="1" selected>Yes</option>
</select>
Run Code Online (Sandbox Code Playgroud)

使用Javascript:

//find the selects in the DOM
var first = document.getElementById('first');
var second = document.getElementById('second');

//this is the handler function we will run when change event occurs
var handler = function () {
    //inside the handler, "this" should be the select 
    //whose change event we are currently handling

    //get the current value and invert it (0 -> 1, 1 -> 0)
    var invertedValue = this.value === '0' ? 1 : 0;

    //check which select's change we are currently handling
    //and set the inverted value as the other select's value
    if (this === first) {
        second.value = invertedValue;
    } else {
        first.value = invertedValue;
    }

};

//add handler function to run on change event on both selects
first.addEventListener('change', handler, false);
second.addEventListener('change', handler, false);
Run Code Online (Sandbox Code Playgroud)