How to set optgroup in select2 using JSON
Asked Answered
T

1

16

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
    });
Trahan answered 22/12, 2015 at 19:52 Comment(2)
there is no example for this job in site, developer use '$(".js-source-states").html();' for fill them. and remove object after fillingArmyn
so, there is no way for filling select only using JSON objects?Trahan
E
27

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>
Eufemiaeugen answered 22/12, 2015 at 20:26 Comment(1)
Great! I've tested in my project and its working as expected! ThanksTrahan

© 2022 - 2024 — McMap. All rights reserved.