function preventDupes( select, index ) {
var options = select.options,
len = options.length;
while( len-- ) {
options[ len ].disabled = false;
}
select.options[ index ].disabled = true;
if( index === select.selectedIndex ) {
alert('You\'ve already selected the item "' + select.options[index].text + '".\n\nPlease choose another.');
this.selectedIndex = 0;
}
}
var select1 = select = document.getElementById( 'select1' );
var select2 = select = document.getElementById( 'select2' );
var select3 = select = document.getElementById( 'select3' );
var select4 = select = document.getElementById( 'select4' );
var select5 = select = document.getElementById( 'select5' );
select1.onchange = function() {
preventDupes.call(this, select2, this.selectedIndex );
preventDupes.call(this, select3, this.selectedIndex );
preventDupes.call(this, select4, this.selectedIndex );
preventDupes.call(this, select5, this.selectedIndex );
};
select2.onchange = function() {
preventDupes.call(this, select1, this.selectedIndex );
preventDupes.call(this, select3, this.selectedIndex );
preventDupes.call(this, select4, this.selectedIndex );
preventDupes.call(this, select5, this.selectedIndex );
};
select3.onchange = function() {
preventDupes.call(this, select1, this.selectedIndex );
preventDupes.call(this, select2, this.selectedIndex );
preventDupes.call(this, select4, this.selectedIndex );
preventDupes.call(this, select5, this.selectedIndex );
};
select4.onchange = function() {
preventDupes.call(this, select1, this.selectedIndex );
preventDupes.call(this, select2, this.selectedIndex );
preventDupes.call(this, select3, this.selectedIndex );
preventDupes.call(this, select5, this.selectedIndex );
};
select5.onchange = function() {
preventDupes.call(this, select1, this.selectedIndex );
preventDupes.call(this, select2, this.selectedIndex );
preventDupes.call(this, select3, this.selectedIndex );
preventDupes.call(this, select4, this.selectedIndex );
};
我试图禁用已经选择的下拉字段,但它只禁用最后选择的下拉值。我想要的是;
当用户首先选择会计时,应该在其他4个下拉列表中禁用。然后,如果用户选择生物学,则必须在其他3个下拉列表中禁用生物学和会计。因此用户可以设置前五个选项
如果你想看看行动中的代码,我有prepared a fiddle。
它减少了问题中onchange
处理程序的大量重复。
为了便于阅读,我将代码拆分为多个部分:
0)定义jQuery选择器,以便不必重复代码:
var selects = '#first, #second';
1)在数组中保留选定的值:
var selectedValues = [];
2)更新选定的值:
var updateSelected = function() {
selectedValues = [];
jQuery(selects).each(function() {
selectedValues.push(jQuery(this).val());
});
}
3)禁用已在其中一个选择中选择的选项。所选选项本身永远不会被禁用,因为这对用户来说看起来很奇怪,并且会导致浏览器在表单提交时不发送值。
var disableOptions = function() {
jQuery(selects).each(function() {
var select = this;
$(this).children('option').each(function() {
if (selectedValues.indexOf($(this).val()) > -1 && $(select).val() != $(this).val()) {
$(this).attr('disabled', true);
} else {
$(this).removeAttr('disabled');
}
});
});
}
4)onchange处理程序
jQuery(selects).change(function(event) {
updateSelected();
disableOptions();
});