jQuery <select> option disabled if selected in multiple <select> boxes

后端 未结 2 1519
闹比i
闹比i 2020-12-12 07:27

I have a question similar to the one asked here: jQuery

But, mine varies in that there will be mor

相关标签:
2条回答
  • 2020-12-12 07:42

    You could do:

    <div>
        <select id='1' name="homepage_select_first">
            <option value=''>No Match</option>
            <option value="1">Test</option>
            <option value="2">Test 2</option>
            <option value="3">Test 3</option>
        </select>
    </div>
    <div>
        <select id='2' name="homepage_select_second">
            <option value=''>No Match</option>
            <option value="1">Test</option>
            <option value="2">Test 2</option>
            <option value="3">Test 3</option>
        </select>
    </div>
    <div>
        <select id='3' name="homepage_select_third">
            <option value=''>No Match</option>
            <option value="1">Test</option>
            <option value="2">Test 2</option>
            <option value="3">Test 3</option>
        </select>    
    </div>
    $('select[name*="homepage_select"]').change(function() {
        var selectedOptions = $('select option:selected');
        $('select option').removeAttr('disabled');
        selectedOptions.each(function() {
            var value = this.value;
            if (value != ''){           
            var id = $(this).parent('select').attr('id');
            var options = $('select:not(#' + id + ') option[value=' + value + ']');
            options.attr('disabled', 'true');
            }
        });
    
    
    });
    

    fiddle here: http://jsfiddle.net/8AcN4/2/

    0 讨论(0)
  • 2020-12-12 07:58

    This should do it. Basically does what your comments ask - ensures that all 3 selects have unique selections. Once a selection is made in 1 selext box that option is no longer available in the others.

    $('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);
            });
        });
    
    });
    

    Live example: http://jsfiddle.net/QKy4Y/

    0 讨论(0)
提交回复
热议问题