如何在多个选择中为每个optgroup仅选择一个值

时间:2014-12-26 08:07:50

标签: jquery

嗨我使用下拉列表,我需要为每个optgroup选择单个值,选择时禁用该optgroup中的其他值

    <select style="width:300px">
    <optgroup label="Alaskan/Hawaiian Time Zone">
   <option value="AK">Alaska</option>
    <option value="HI">Hawaii</option>
    </optgroup>
   <optgroup label="Pacific Time Zone">
   <option value="CA">California</option>
   <option value="NV">Nevada</option>
   <option value="OR">Oregon</option>
   <option value="WA">Washington</option>
   </optgroup>
   </select>




$('select').change(function () {
var opt = $(this).find(':selected');
var sel = opt.text();
var og = opt.closest('optgroup').attr('label');
//alert(sel);
//alert(og);
     var selects = $('select option').attr('id');
 for (var i=0; i<selects.length; i++) {
    $(selects[i]).find('option').removeAttr('disabled'); 
  }

});

2 个答案:

答案 0 :(得分:1)

http://jsfiddle.net/yL60hp9o/3/

$select = $("#msel").select2();
$select.on('change', function (event) {
    if (event.added) {
        var selected = $select.find('option[value="'+event.added.id+'"]');
        selected.closest('optgroup').find('option').each(function(k, i) { 
            if ( $(i).val() != selected.val() )
                $(i).prop('disabled', true);
        });
    }
    else if (event.removed) {
        var parent = $select.find('option[value="'+event.removed.id+'"]');
        parent.closest('optgroup').find('option').each(function(k, i) { 
            $(i).prop('disabled', false);
        });  
    }
});

您需要将multiple添加到select

答案 1 :(得分:0)

您需要为此选择更新此jQuery代码

 <select class="form-control" name="member_class" id="member_class" multiple="multiple"> 
    <optgroup label="Swedish Cars">
       <option value="volvo">Volvo</option>
       <option value="saab">Saab</option> 
    </optgroup>
    <optgroup label="German Cars"> 
       <option value="mercedes">Mercedes</option> 
       <option value="audi">Audi</option> 
    </optgroup>
 </select>
<script>
    $('#member_class[multiple="multiple"] option').click(function(){
         $(this).closest('optgroup').find('option').prop('selected',false);
         $(this).prop('selected',true);
    });
</script>