2014-08-29 146 views
1

我試圖讓jQuery插件選擇2到動態更新使用JSON動態添加OPTGROUP列表

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"}]}] 

和選擇2的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。

任何幫助將不勝感激。

回答

2

解決它......

在JSON改變了這個( '名' 到 '文本'):

[{"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( '名' 到 '文本'):

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, 
});