jQuery Bootstrap selectpicker显示optgroup

时间:2019-02-28 15:17:44

标签: javascript jquery bootstrap-selectpicker

这是演示

  <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

寻求帮助!

1 个答案:

答案 0 :(得分:0)

尝试一下...

$(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