动态添加optgroup列表

时间:2014-08-29 11:24:40

标签: jquery json jquery-select2

我正在尝试使用json

动态更新jQuery插件select2

JSON'optionString':

[{"text":"A","children":[{"id":"313","name":"Adair, Graham"}]},{"text":"B","children":[{"id":"396","name":"Boots, Benjamin"}]},{"text":"M","children":[{"id":"616","name":"Marshall, James"},{"id":"361","name":"Montgomery, Kirsty"}]}]

和select2 javascript:

var names = jQuery.parseJSON(optionString);

function format(item) { return item.name; };
$("#nameSearchSel").select2({
        placeholder: "Name Search",
        data:{ results: names, text: 'name' },
        formatSelection: format,
        formatResult: format,
});

HTML:

<input id="nameSearchSel" type="hidden" style="width:190px;"/>

这会更新select2,但会删除所有的optgroup。

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:2)

解决了......

在JSON中改变了这一点(&#39;名称&#39;到&#39;文字&#39;):

[{"text":"A","children":[{"id":"313","text":"Adair, Graham"}]},{"text":"B","children":[{"id":"396","text":"Boots, Benjamin"}]},{"text":"M","children":[{"id":"616","text":"Marshall, James"},{"id":"361","text":"Montgomery, Kirsty"}]}]

这是javascript(&#39; name&#39; to&#39; text&#39;):

var names = jQuery.parseJSON(optionString);

function format(item) { return item.text; };
$("#nameSearchSel").select2({
        placeholder: "Name Search",
        data:{ results: names, text: 'text' },
        formatSelection: format,
        formatResult: format,
});