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

时间:2011-06-02 07:59:04

标签: javascript javascript-events combobox

我在表单上有2个组合框。每个都有值Yes和No.我想要的是当一个被改变时另一个得到反面(如果第一个是Yes,另一个是No)。我需要用javascript来做。我看到了这个问题How to change "selected" value in combobox using JavaScript?,但它只适用于一个组合框。

我该怎么做?

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

3 个答案:

答案 0 :(得分:6)

我创建了一个简单的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);

答案 1 :(得分:4)

我相信这就是你要找的东西:

<select id="combo1" onchange="FlipOtherCombo(this, 'combo2')">
    <option value="yes">yes</option>
    <option value="no">no</option>
</select>
<select id="combo2" onchange="FlipOtherCombo(this, 'combo1')">
    <option value="yes">yes</option>
    <option selected="selected" value="no">no</option>
</select>

<script>
    function FlipOtherCombo(objCombo, strOtherComboId){
        if (objCombo.value ==="yes"){
            document.getElementById(strOtherComboId).value = "no";
        } else {
            document.getElementById(strOtherComboId).value = "yes";
        }
    }
</script>

同样在this JSFiddle.

虽然使用单选按钮来表示这样的简单是/否选项更好。

答案 2 :(得分:2)

这是我自己尝试使用是/否值..

<强> HTML

<select name="combo1" id="combo1">
    <option value="Yes">Yes</option>
    <option value="No">No</option>
</select>
<br /><br />
<select name="combo2" id="combo2">
    <option value="Yes">Yes</option>
    <option value="No">No</option>
</select>

<强>的javascript

window.onload = function() { BindEvent(); }

function BindEvent()
{
    var c1 = document.getElementById ( 'combo1' );
    var c2= document.getElementById ( 'combo2' );

    c1.onchange = invert;
    c2.onchange = invert;

    c1.onchange(); //initialize
}

function invert() {
         var otherElem = document.getElementById( (this.id=='combo1')? 'combo2' : 'combo1');
         otherElem.value = (this.value=='Yes')?'No':'Yes';
    }

演示 http://jsfiddle.net/gaby/7Ujh2/