我有一个类似于这里问的问题:
jQuery <select> option disabled if selected in other <select>
但是,我的不同之处在于将有两个以上的选择框.在提供的答案中,当选择一个选项时,在其他选择框(我想要发生)中将其设置为禁用,但我不希望在其他选择框中选择的任何其他选项已禁用删除.
那有意义吗?
示例html:
<div>
<select name="homepage_select_first">
<option>No Match</option>
<option value="1">Test</option>
<option value="2">Test 2</option>
<option value="3">Test 3</option>
</select>
</div>
<div>
<select name="homepage_select_second">
<option>No Match</option>
<option value="1">Test</option>
<option value="2">Test 2</option>
<option value="3">Test 3</option>
</select>
</div>
<div>
<select name="homepage_select_third">
<option>No Match</option>
<option value="1">Test</option>
<option value="2">Test 2</option>
<option value="3">Test 3</option>
</select>
</div>
和jQuery:
$('select[name*="homepage_select"]').change(function() {
var value = $(this).val();
alert(value);
$('select[name*="homepage_select"]').children('option').each(function(){
if ( $(this).val() === value ) {
$(this).attr('disabled',true)//.siblings().removeAttr('disabled');
}
});
});
注释掉.siblings().removeAttr(‘disabled’)只是永远不会删除已禁用的属性…但是,如果未在任何一个选择框中选择它,我只想删除它.
基本上,我只希望一次在一个选项中选择一个选项.我认为如果我只能对刚刚更改的项目进行.removeAttr(‘禁用’),我认为这样可行.但是,我不知道该怎么做.
有没有人有任何想法?
谢谢!
解决方法
这应该做到这一点.基本上是您的评论所要求的 – 确保所有3个选项都有唯一的选择.在1个selext框中进行选择后,其他选项将不再可用.
$('select[name*="homepage_select"]').change(function(){
// start by setting everything to enabled
$('select[name*="homepage_select"] option').attr('disabled',false);
// loop each select and set the selected value to disabled in all other selects
$('select[name*="homepage_select"]').each(function(){
var $this = $(this);
$('select[name*="homepage_select"]').not($this).find('option').each(function(){
if($(this).attr('value') == $this.val())
$(this).attr('disabled',true);
});
});
});
实例:http://jsfiddle.net/QKy4Y/