2013-05-07 25 views
16

這讓我瘋狂!爲什麼不能Select2在他們的頁面上實現清晰的方法或示例如何在Select2上執行簡單的CRUD操作:)Select2 Dropdown動態添加,刪除和刷新項目

我有一個select2,它從ajax調用中獲取數據。

<input id="valueg" type="hidden" style="width: 300px;" data-placeholder="Select a Conference" /> 

$("#valueg").select2({ 
      data: conferences, 
      allowClear: true, 
      initSelection: function (element, callback) { 
          var data = { id: element.val(), text: element.val() }; 
          callback(data); 
         } 
}).on("change", function (e) { 
// show data in separate div when item is selected    
}); 

有人能提供清晰的方法如何刪除,並從選擇二加一項目。

例如:

我通過Ajax調用項目添加到數據庫,只是想追加一個選項,選擇二,並將其設置爲選中狀態。

我通過ajax刪除一個項目到數據庫,並且想要從Select2中刪除一個選項並且沒有選擇任何選項。

回答

17

從你的例子我可以看到你將Select2插件附加到隱藏的元素。此外,您在這種情況下使用Ajax調用來填充的效果,所以如果你需要一個新的選項添加到列表中,您簡單的調用:

$('#valueg').select2('val', 'YOUR_VALUE'); 

在使用select元素作爲容器的唯一途徑的情況下,我發現是用新選項重新初始化插件...類似這樣的:

var el = $('select[name="type"]', '#details-form'); 
var temp = el.select2('val'); // save current value 
temp.push(NEW_VALUE); // append new one 
var newOptions = '<option value="1">1</option><option value="2">2</option>'; 
el.select2('destroy').html(newOptions).select2().select2('val', temp); 
4

我有同樣的問題。這是我如何解決它

這有什麼好做選擇2,操縱本身似乎爲我

2

我做到了以這種方式工作:

var $select2 = $('#valueg').select2(); // getting the select2 
var item = 'xyz'; // item to be added 
$select2.val(function(i, val) { // val can take function as parameter 
    val = val || []; // if value is null init val as an array 
    val.push(item); // add the new item 
    return val; 
}).trigger("change"); //refresh 

希望幫助

0

現在太晚了...但這是我仍然有這個問題的人的解決方案:

html = ""; 
jQuery("#select_2 option").each(function() 
{ 
    html += '<option value="'+jQuery(this).attr("value")+'">'+jQuery(this).text()+'</option>'; 
}); 
html += '<option value="NEWVALUE">NEW OPTION</option>'; 
jQuery("#select_2").html(html); 
0

在我的情況下,操縱底層的選擇後添加的關鍵是:

$ selectlist.trigger(「變」); // $ selectlist是底層的select元素。

Select2在select上的變化事件上工作,所以調用「change」更新select 2中顯示的選項。