Search code examples
javascriptjquerybootstrap-selectpicker

JQuery Bootstrap selectpicker show optgroup


here is the demo

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

when i use selectpicker and choose one or more options, it shows like a,b or a,c,d i want to show like Label1-a,b or Label1-a,Label2-c,d

thx for help!


Solution

  • Try this...

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