[英]Append options to select2
I have the following select: 我有以下选择:
<select id="street" name="client[street_id]" class="form-control select2" data-placeholder="Select or Insert The Street" style="width: 100%;">
@foreach($streets as $street)
<option value="{{ $street->id }}">{{ $street->name }}</option>
@endforeach
</select>
And the initialisation: 和初始化:
$(".select2").select2({tags: true});
Note that multiple has not been set to true. 注意,倍数尚未设置为true。 The problem is when I enter a new option (tag), first time will add the tag but second time will replace the first one in the list. 问题是当我输入一个新选项(标签)时,第一次将添加标签,但是第二次将替换列表中的第一个标签。 So how can I add options in the select and keep them? 那么,如何在选择中添加选项并保留它们呢? (on each add I will make a request to server to save to db). (在每个添加项上,我都会向服务器发出请求以保存到数据库)。
https://jsfiddle.net/8c7ujd4g/ https://jsfiddle.net/8c7ujd4g/
I found this solution: 我找到了这个解决方案:
$('.select2').on("select2:select", function(e) {
// what you would like to happen
if(e.params.data.isNew){
$(this).find('[data-select2-tag="true"]').replaceWith($('<option selected>', { value : e.params.data.id })
.text(e.params.data.text));
$.ajax({
// ...
});
}
});
$(".select2").select2({tags: true,
createTag: function (params) {
var term = $.trim(params.term);
if (term === '') {
return null;
}
return {
id: term,
text: term,
isNew: true // add additional parameters
}
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.