Dynamically adding options and optgroups in Select2
Asked Answered
A

2

23

With the following html:

<input type='hidden' id='cantseeme'>

I'm having no trouble creating a Select2 control dynamically, and adding my options:

// simplified example
var select2_ary = [];

select2_ary.push({
    id : "one",
    text : "one"
});
select2_ary.push({
    id : "two",
    text : "two"
});

$("#cantseeme").select2({
    placeholder : "Pick a number",
    data : select2_ary
});

However, I can't seem to figure out how to add optgroups this way. I found this discussion on github, and this article on a blog, but the former doesn't seem to discuss dynamic optgroup additions and I simply can't make any sense of the latter.

Anyone have any ideas?

Avifauna answered 20/8, 2013 at 23:24 Comment(0)
A
33

I found the answer buried inside the github discussion you linked to, the object structure for optgroups is as follows:

{
  id      : 1,
  text    : 'optgroup',
  children: [{
                id  : 2,
                text: 'child1'
             },
             {
                id      : 3,
                text    : 'nested optgroup', 
                children: [...]
             }]
}

Demo fiddle

Agave answered 20/8, 2013 at 23:55 Comment(2)
facepalm Thanks very much. I feel so dumb for missing that. Tbh, surprised that no one else has asked that before on here!Avifauna
koala_dev, it looks like the fiddle you posted no longer worksCountermarch
S
25

Yes, koala_dev's answer above is correct. However, if you do not want option group headers to be selectable tags, then remove the "id" field from headers that you pass into select2. Children[ ] items still need an "id" field to be selectable. For example:

// `Header One` Is Selectable
[{
    id       : 0,
    text     : "Header One",
    children : [{
        id   : 0,
        text : "Item One"
    }, { 
        ...
    }]
}] 


// `Header One` Is Not Selectable
[{
    text     : "Header One",
    children : [{
        id   : 0,
        text : "Item One"
    }, { 
        ...
    }]
}] 
Shanika answered 17/5, 2014 at 4:20 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.