Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set optgroup in select2 using JSON

How some items can be group in separate optgroups? Should be set in different JSON objects? There is no example in select2 documentation. Any help or direction would be helpful.

Here is example code of select population:

jQuery code:

 var data = [
          { id: 0, text: 'enhancement' }, 
          { id: 1, text: 'bug' }, 
          { id: 2, text: 'duplicate' }, 
          { id: 3, text: 'invalid' }, 
          { id: 4, text: 'wontfix' }
    ];

    $(".js-example-data-array").select2({
      data: data
    });
like image 310
Brane Avatar asked Dec 22 '15 19:12

Brane


1 Answers

You need to set children attribute in your array to allow optgroups.

Example : https://jsfiddle.net/DinoMyte/8odneso7/13/

var data = [{
    id: 0,
    text: 'enhancement',
    children: [{
        id: 5,
        text: 'enhancement child1'
      },
      {
        id: 6,
        text: 'enhancement child2'

      }
    ]
  },
  {
    id: 1,
    text: 'bug'
  },
  {
    id: 2,
    text: 'duplicate'
  },
  {
    id: 3,
    text: 'invalid'
  },
  {
    id: 4,
    text: 'wontfix'
  }
];

$(".js-example-data-array").select2({
  data: data,
  width: 'auto'
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"></script>
<select class="js-example-data-array">
</select>
like image 127
DinoMyte Avatar answered Oct 20 '22 11:10

DinoMyte