【发布时间】:2016-03-14 00:26:55
【问题描述】:
我实现了一个标签系统,您可以在其中选择现有标签或添加新标签。选择新标签后,它将使用 AJAX 调用保持不变。
为了实现这一点,我使用了回调 createTag 和事件 select2:select。因为我喜欢仅在选中标签时创建标签,所以如果事件 select2:select 被触发,我会为此进行 AJAX 调用。
问题是我需要使用从将新标签保存到数据库中获得的 ID 更新已创建的 select2 选项。最干净的解决方案是什么?
这是我所拥有的:
$('select.tags').select2({
tags: true,
ajax: {
url: '{{ path('tag_auto_complete') }}',
processResults: function (data) {
return {
results: data.items,
pagination: {
more: false
}
};
}
},
createTag: function (tag) {
return {
id: tag.term, // <-- this one should get exchanged after persisting the new tag
text: tag.term,
tag: true
};
}
}).on('select2:select', function (evt) {
if(evt.params.data.tag == false) {
return;
}
$.post('{{ path('tag_crrate_auto_complete') }}', { name: evt.params.data.text }, function( data ) {
// ----> Here I need to update the option created in "createTag" with the ID
option_to_update.value = data.id;
}, "json");
});
【问题讨论】:
-
您是否尝试过在标签创建后触发更改事件?
-
@BuddhistBeast 这对我有帮助吗?如果我听这个事件,我的 ID 已经没了?还是我应该听 change 事件而不是 select 事件?
标签: javascript jquery jquery-select2 jquery-select2-4