With the following html:
以下html:
<input type='hidden' id='cantseeme'>
I'm having no trouble creating a Select2 control dynamically, and adding my options:
动态地创建Select2控件,并添加我的选项:
// 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.
然而,我似乎不知道如何以这种方式添加optgroups。我在github上找到了这个讨论,在博客上找到了这篇文章,但是前者似乎并没有讨论动态optgroup的添加,而我根本无法理解后者。
Anyone have any ideas?
谁有什么好主意吗?
2 个解决方案
#1
34
I found the answer buried inside the github discussion you linked to, the object structure for optgroups
is as follows:
我在你链接的github讨论中找到了答案,optgroups的对象结构如下:
{
id : 1,
text : 'optgroup',
children: [{
id : 2,
text: 'child1'
},
{
id : 3,
text : 'nested optgroup',
children: [...]
}]
}
演示小提琴
#2
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:
是的,koala_dev上面的答案是正确的。但是,如果不希望选项组标头是可选择的标记,则从传递到select2的标头中删除“id”字段。子项[]仍然需要一个“id”字段才能选择。例如:
// `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"
}, {
...
}]
}]
#1
34
I found the answer buried inside the github discussion you linked to, the object structure for optgroups
is as follows:
我在你链接的github讨论中找到了答案,optgroups的对象结构如下:
{
id : 1,
text : 'optgroup',
children: [{
id : 2,
text: 'child1'
},
{
id : 3,
text : 'nested optgroup',
children: [...]
}]
}
演示小提琴
#2
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:
是的,koala_dev上面的答案是正确的。但是,如果不希望选项组标头是可选择的标记,则从传递到select2的标头中删除“id”字段。子项[]仍然需要一个“id”字段才能选择。例如:
// `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"
}, {
...
}]
}]