如果在多个<select>框中选中,则禁用jQuery <select>选项

idd*_*imu 0 jquery jquery-selectors

我有一个问题类似于这里提出的问题:如果在其他<select>中选中,则禁用jQuery <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>
Run Code Online (Sandbox Code Playgroud)

和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');  

        }
    });

});
Run Code Online (Sandbox Code Playgroud)

注释掉.siblings().removeAttr('disabled')只是永远不会删除已禁用的属性...但是,如果未在任何一个选择框中选择它,我只想将其删除.

基本上,我只想在其中一个选项中选择一个选项.我认为,如果我只能.removeAttr('disabled')对刚改变的项目进行处理,我认为这样可行.但是,我不知道该怎么做.

有没有人有任何想法?

谢谢!

Jam*_*iec 7

这应该做到这一点.基本上是您的评论所要求的 - 确保所有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);
        });
    });

});
Run Code Online (Sandbox Code Playgroud)

实例:http://jsfiddle.net/QKy4Y/