我需要更新一个数组数据源。使用https://stackoverflow.com/a/28271338/161457中的重置/清除技术不会清除选项;控件将它们组合在一起(代码片段中有一个,两个,三个,四个)。如何清除控件并重新初始化选项?
$(function () {
var initialData = [{ id: 1, text: 'one' }, { id: 2, text: 'two' }];
$("#test").select2({
data: initialData
});
$('#change').click(function () {
var newData = [{ id: 3, text: 'three' }, { id: 4, text: 'four' }];
$('#test').val([]); // Attempt to clear
$("#test").select2({
data: newData
});
});
});
@import url('https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css');
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"></script>
<form>
<select id="test" name="test" multiple="multiple" style="width: 50%"></select>
</form>
<button type="button" id="change">Change</button>
答案 0 :(得分:2)
不幸的是,使用原生Select2功能无法做到这一点,必须手动完成。
请参阅此GitHub问题:https://github.com/select2/select2/issues/2830
基本上,您需要销毁Select2实例,然后通过重新初始化它再次重新填充它。下面的代码快速而肮脏,我确信有更好的方法来编写它:
$(function () {
var initialData = [{ id: 1, text: 'one' }, { id: 2, text: 'two' }];
//good practice to cache your jquery objects:
var $test = $("#test");
$test.select2({
allowClear: true,
data: initialData
});
$('#change').click(function () {
var newData = [{ id: 3, text: 'three' }, { id: 4, text: 'four' }];
//clear chosen items
$test.val("").change();
//destroy select2
$test.select2("destroy");
//remove options physically from the HTML
$test.find("option").remove();
//re-initialize with new data
$test.select2({
data: newData
});
});
});
@import url('https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css');
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"></script>
<form>
<select id="test" name="test" multiple="multiple" style="width: 50%"></select>
</form>
<button type="button" id="change">Change</button>
答案 1 :(得分:1)
当我运行AJAX请求并用新项填充select2时,我就是这样做的:
var categoryGroups = response.data;
$.each(categoryGroups, function (key, categoryGroup) {
$groupList.append(
'<option value="' + categoryGroup.id + '">' +
categoryGroup.name +
'</option>'
);
});
$groupList.change();
$groupList
是select元素的选择器。
更新:
另一种方法是做一些事情:
$('#test').empty()
$('#test').select2({data: newData})