JQuery Bootstrap 选择器显示 optgroup

JQuery Bootstrap selectpicker show optgroup

这是演示

  <select class="selectpicker" multiple name="selectpickerdemo"
      id="selectpickerdemo"> 
    <optgroup label="Label 1">
      <option value='a'>a</option>
      <option value='b'>b</option>
    </optgroup>
    <optgroup label="Label 2">
      <option value='c'>c</option>
      <option value='d'>d</option>
    </optgroup> 
  </select>

当我使用 selectpicker 并选择一个或多个选项时, 它显示为 a,ba,c,d 我想表现得像 Label1-a,bLabel1-a,Label2-c,d

谢谢帮助!

试试这个...

$(document).on('change', '.selectpicker', function() {
  var SelectedValues = [];
  $(this).find('optgroup').each(function() {
    var OptionGroupSelected = [];
    $(this).find('option').each(function() {
      if ($(this).prop('selected')) {
        OptionGroupSelected.push($(this).val());
      }
    });
    if (OptionGroupSelected.length > 0) {
      var Label = $(this).attr('label').replace(' ', '');
      SelectedValues.push(Label + '-' + OptionGroupSelected.join(','));
    }
  });
  console.log(SelectedValues);
});

Here is the fiddle