我正在向select2添加一个新项目。当这种情况发生时,我会触发一个onChange AJAX请求。AJAX请求将新项添加到DB中,并返回已插入行的id。
ATM机中,select2中添加的选项的值包含我输入的原始字符串值。我想要更新select2中那个特定选项的值,以便它成为从AJAX调用返回的数据库行的id。
下面是JS:
$('.my-select2').on('change', function() {
$.ajax({
type: 'POST',
url: '/ajax/groups/saveGroup',
data: {
"_token": "{{ csrf_token() }}",
"value": this.value
},
dataType: 'json',
success: function(data){
console.log(data); // this equals the id of the row in the db,
// and it's what I want to make into the value of
// the option that's been added.
// I've tried many more than the following and none have worked.
// $(this).attr("value", data);
// $(this).val(data).change();
// $(this).select2("val", data);
// $('.my-select2').select2('data', {id: data, text: 'original value'});
}
});
请帮帮忙,我没主意了,也没办法在谷歌上搜索了。
发布于 2020-01-12 01:45:33
我在这个函数之外使用了一个单独的AJAX函数来解决这个问题,该函数从db中检索所有记录并重新绘制整个select2控件。它稍微贵一点,但也能做这件事。
https://stackoverflow.com/questions/59694785
复制相似问题