我在窗體上有2個組合框。每個人都有「是」和「否」的值。我想要的是當其中一個更改時,另一個則相反(如果第一個是「是」,另一個是「否」)。我需要使用javascript來完成。我看到這個問題How to change "selected" value in combobox using JavaScript?,但它只適用於一個組合框。Javascript - 其他組合框的combobox更改值
我該怎麼做? LE:我需要使用組合框來製作這個例子。我不能使用單選按鈕
我在窗體上有2個組合框。每個人都有「是」和「否」的值。我想要的是當其中一個更改時,另一個則相反(如果第一個是「是」,另一個是「否」)。我需要使用javascript來完成。我看到這個問題How to change "selected" value in combobox using JavaScript?,但它只適用於一個組合框。Javascript - 其他組合框的combobox更改值
我該怎麼做? 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);
我相信這是你在找什麼:
在 this JSFiddle.雖然
<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>
此外,使用單選按鈕簡單的是/像這樣沒有選擇比較好。
我應該注意到,我一直懶我的內聯'onclick'綁定。 @ bazmegakapa的答案更好,因爲它在JavaScript中執行綁定 – 2011-06-02 08:20:55
這裏是有工作我自己嘗試/沒有值..
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';
}
如果僅僅是/否,爲什麼你使用'combobox'並使其複雜,只要使用'checkbox',你可以很容易地翻轉它.. – niksvp 2011-06-02 08:01:25
甚至更適合設計的單選按鈕和分組! – 2011-06-02 08:03:52