TiM*_*TER 8 javascript jquery jquery-select2 jquery-select2-4
我实现了一个标记系统,您可以从中选择现有标记或添加新标记.选择新标签后,它将持续使用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");
});
Run Code Online (Sandbox Code Playgroud)
我的问题是我没有将新标签作为<option>标签添加到本机选择字段.
这是必要的,因为select2.val(values)如果<option>存在具有此值的标记,则select2将检查设置的值.如果不是,则select2以静默方式将值抛出数组,并设置在基础选择字段中具有相应选项标记的值数组.
所以这就是它现在正常工作的方式(对于select2 4.0.x):
$('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,
text: tag.term,
tag: true
};
}
}).on('select2:select', function (evt) {
if(evt.params.data.tag == false) {
return;
}
var select2Element = $(this);
$.post('{{ path('tag_crrate_auto_complete') }}', { name: evt.params.data.text }, function( data ) {
// Add HTML option to select field
$('<option value="' + data.id + '">' + data.text + '</option>').appendTo(select2Element);
// Replace the tag name in the current selection with the new persisted ID
var selection = select2Element.val();
var index = selection.indexOf(data.text);
if (index !== -1) {
selection[index] = data.id.toString();
}
select2Element.val(selection).trigger('change');
}, 'json');
});
Run Code Online (Sandbox Code Playgroud)
最小的AJAX响应(JSON格式)必须如下所示:
[
{'id': '1', 'text': 'foo'},
{'id': '2', 'text': 'bar'},
{'id': '3', 'text': 'baz'}
]
Run Code Online (Sandbox Code Playgroud)
您可以为每个结果添加其他数据,让我们自己渲染结果列表并在其中添加其他数据.