我的表单上有两个组合框。每个都有值 Yes 和 No。我想要的是当一个改变时另一个得到相反的结果(如果第一个是 Yes,另一个是 No)。我需要用 Javascript 来做。我看到这个问题如何使用 JavaScript 更改组合框中的“选定”值? https://stackoverflow.com/questions/1778184/how-to-change-selected-value-in-combobox-using-javascript但它仅适用于一个组合框。
我怎样才能做到这一点?
LE:我需要用组合框制作这个示例。我无法使用单选按钮
我创建了一个简单的jsFiddle 演示 http://jsfiddle.net/pFuJQ/78/。这并不完美,只是说明了这个想法。
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>
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);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)