Javascript - 组合框改变其他组合框的值 [英] Javascript - combobox change value of other combobox

查看:156
本文介绍了Javascript - 组合框改变其他组合框的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have 2 comboboxes on an form. Each has the values Yes and No. What I want is when one is changed the other get the opposite (if the first is Yes the other is No).I need to do it with javascript. I saw this question How to change "selected" value in combobox using JavaScript? but it is applied to only one combobox.

我该怎么办?

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

LE:I need this example to be make with comboboxes. I can not use radio buttons

推荐答案

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

I created a simple jsFiddle Demo. This is not perfect, just illustrates the idea.

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 - 组合框改变其他组合框的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆