在Select2中动态添加选项和选项组

Dynamically adding options and optgroups in Select2

本文关键字:选项 添加 动态 Select2      更新时间:2023-09-26

使用以下html:

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

我在动态创建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
});

然而,我似乎不知道如何以这种方式添加optgroups。我在github上找到了这个讨论,在博客上也找到了这篇文章,但前者似乎没有讨论动态optgroup添加,我根本无法理解后者。

有人有什么想法吗?

我在你链接的github讨论中找到了答案,optgroups的对象结构如下:

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

演示小提琴

是的,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"
    }, { 
        ...
    }]
}]