Select2下拉列表动态添加,删除和刷新项目 [英] Select2 Dropdown Dynamically Add, Remove and Refresh Items from
问题描述
这让我抓狂!为什么不能让Select2在他们的页面上实现清晰的方法或示例如何在Select2上进行简单的CRUD操作:)
This drives me crazy! Why cant Select2 implement clear methods or examples on their page how to do simple CRUD manipulation on Select2 :)
我有一个select2,它从ajax调用中获取数据。
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
});
有人可以提供一个清除方法,如何从Select2中删除和添加项目。
Can some one provide a clear method how to delete and add an item from the Select2.
例如:
我通过ajax调用db添加一个项目,只想添加一个选项选择2并将其设置为选中。
I add an item via ajax call to db, and just want to append an option to Select2 and set it as selected.
我通过ajax删除项目到db,并且想要从Select2中删除一个选项并且没有选择任何选项。
I remove an item via ajax to db, and want to remove an option from Select2 and have no option selected.
推荐答案
从您的示例中我可以看到您将Select2插件附加到隐藏元素。此外,您使用Ajax调用来填充结果,因此在这种情况下,如果您需要向列表添加新选项,则可以简单地调用:
From your example I can see that you attached Select2 plugin to hidden element. In addition you use Ajax call to populate results, so in this case if you need to add a new option to the list you simple call:
$('#valueg').select2('val', 'YOUR_VALUE');
如果使用select元素作为容器,我找到的唯一方法是使用new重新初始化插件选项......这样的事情:
In case of using select element as a container the only way that I found is to reinitialize plugin with new options... Something like this:
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);
这篇关于Select2下拉列表动态添加,删除和刷新项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!