18

This drives me crazy! Why cant Select2 implement clear methods or examples on their page how to do simple CRUD manipulation on Select2 :)

i have a select2 which gets data from a ajax call.

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

Can some one provide a clear method how to delete and add an item from the Select2.

For example:

I add an item via ajax call to db, and just want to append an option to Select2 and set it as selected.

I remove an item via ajax to db, and want to remove an option from Select2 and have no option selected.

4

5 回答 5

17

从您的示例中,我可以看到您将 Select2 插件附加到隐藏元素。此外,您使用 Ajax 调用来填充结果,因此在这种情况下,如果您需要向列表中添加新选项,您只需调用:

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

如果使用选择元素作为容器,我发现的唯一方法是使用新选项重新初始化插件......像这样:

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);
于 2013-05-30T11:41:35.677 回答
4

我遇到过同样的问题。这就是我解决它的方法

这与select2无关,操纵本身似乎对我有用

 $("#lstService").empty();
  for(var i=0;i<data.length;i++){
     $("#lstService").append('<option value="'+data[i].service_id+'">'+data[i].service_name+'</option>');
 }
于 2014-11-08T18:32:41.100 回答
4

我是这样做的:

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

希望有帮助

于 2016-02-24T14:47:15.847 回答
1

就我而言,在操作底层选择之后要添加的关键是:

$selectlist.trigger("change");//$selectlist 是底层的选择元素。

Select2 可以解决 select 上的 change 事件,因此调用“change”会更新 select 2 中显示的选项。

于 2016-11-29T09:18:25.097 回答
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);
于 2016-03-17T12:28:40.107 回答