我正在使用带有标签选项的mutliselect2。当用户输入不在列表中的标签时(例如:aab),它将打开一个模式并将该标签插入数据库。 我想将新创建的标签的值从“ aab”更改为标签插入后返回的id。
<div class="form-group" id="tagsDiv">
<label class="main">{{__('messages.Tags')}}</label>
<div class="input-group">
{{ Form::hidden('tagids',old('tagids') ?? '',['class'=> 'form-control','id'=>'tagids']) }}
{{ Form::select('tags[]',$tag_master, old('tags') ?? '', ['class'=> 'form-control '.(Auth::user()->votesCount() > $min_points_for_tag ? 'select2-tags' : 'm-select2'),'id'=> (Auth::user()->votesCount() > $min_points_for_tag ? 'select2_tags' : 'm_select2_tags'), 'data-plugin'=>'select2','multiple'=>true, 'style'=>'width:100%']) }}
</div>
</div>
这是select2的js代码
$('.select2-tags').select2({
minimumInputLength: 2,
tags: true,
tokenSeparators: [",", " "],
ajax: {
url: "{{route('getTagsAjax')}}",
dataType: 'json',
delay: 250,
data: function (params) {
return {
search: params.term,
page: params.page || 1,
category_id : $("#qcategory_id").val(),
specialty_id : $("#m_select2_speciality").val()
};
},
processResults: function (data, params) {
params.page = params.page || 1;
return {
results: $.map(data.data, function (item) {
return {
text: item.title,
id: item.id
}
}),
pagination: {
more: (params.page * 10) < data.total
}
};
},
cache: true
}
});
此代码在选择标签时打开模式
$('.select2-tags').on('select2:select', function (e) {
var specialty = $("#m_select2_speciality");
var data = [];
$('[name="specialities[]"] option:selected').each(function(){
var option = $(this);
data.push({value : option.attr('value'), text : option.text()});
})
if(isNaN(e.params.data.id)){
$('#addTagModal').modal();
$('#addTagModal #tagTitle').val(e.params.data.id);
$.each(data,function(index,json){
var value = data[index].value;
var exists = $("#selectSpeciality option")
.filter(function (i, o) { return o.value === value; })
.length > 0;
if (!exists) {
$("#selectSpeciality").append($("<option></option>").attr("value", data[index].value).text(data[index].text));
}
});
}
});
这是在模式提交时执行的代码
$(document).on('click', '#addTagDetails' , function(e) {
e.preventDefault();
$.ajax( {
url:'{{route("ajaxAddTag")}}',
type: 'POST',
data: $("#formTagDetails").serialize(),
success:function(result) {
$('#addTagModal').modal('hide');
if(result.status == 'success'){
Swal.fire({
text: result.message,
type: "success",
});
}else {
Swal.fire({
text: result.message,
type: "error",
});
}
}
});
});
请帮助我找到解决方法