gpt4 book ai didi

javascript - 其他组合框的组合框更改值

转载 作者:行者123 更新时间:2023-12-02 05:53:31 26 4
gpt4 key购买 nike

我在一个表单上有两个组合框。每个都有值 Yes 和 No。我想要的是当一个改变时另一个得到相反的结果(如果第一个是 Yes 另一个是 No)。我需要用 Javascript 来完成。我看到了这个问题How to change "selected" value in combobox using JavaScript?但它只应用于一个组合框。

我该怎么做?

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

最佳答案

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

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

关于javascript - 其他组合框的组合框更改值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6211929/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com