Select2 多个 select 和允许的标签的默认值

Select2 Default values for multiple select and allowed tags

我有一个 select 2 multi-select 选项

<select multiple name="event_type[]" class="form-control" id="selectEvents">
   @foreach ($eTypes as $type)
       <option>{{$type}}</option>
   @endforeach
</select>

我想设置一些默认值以防用户编辑表单。 我已经通过这样做成功地做到了

var s2 = $("#selectEvents").select2({
    placeholder: "Choose event type",
    tags: true
});

s2.val(["Trade Fair", "CA", "Party"]).trigger("change"); //CA doesn't show as a default

但问题是我允许用户使用 select2 的 tags: true 选项生成选项。

当我设置一个最初在 html 选项中的默认值时它起作用,但是当我设置一个由用户生成的默认值时它不起作用。

这是我第一次使用 select2。

我怎样才能做到这一点?

稍作挖掘,我可以在 GitHub 上看到这个问题。

一个选项是检查该值是否存在,如果不存在,append它。

var s2 = $("#selectEvents").select2({
    placeholder: "Choose event type",
    tags: true
});

var vals = ["Trade Fair", "CA", "Party"];

vals.forEach(function(e){
if(!s2.find('option:contains(' + e + ')').length) 
  s2.append($('<option>').text(e));
});

s2.val(vals).trigger("change"); 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.css" rel="stylesheet"/>

<select multiple name="event_type[]" class="form-control" id="selectEvents">
  <option>Trade Fair</option>
  <option>Party</option>
  <option>Foo</option>
  <option>Bar</option>
</select>

我最近不得不在 PHP 脚本中实现带有选项 'multiple' 和 'tags' 的 select2,并且 运行 遇到了类似的问题。文档说将任何初始选择添加为 html 选项标签,但是当我尝试添加两个时,只有一个会显示在我的 select2 控件中。

我最终使用动态创建的配置对象 'data' 选项初始化了 select2 控件。

var initialPropertyOptions = [];
@foreach ($model->properties as $initialProperty`)
    var initialPropertyOption = {
        id:         {{ $initialProperty->id }},
        text:       '{{ $initialProperty->name }}',
        selected:   true
    }
    initialPropertyOptions.push(initialPropertyOption);
@endforeach

$('#properties').select2({
    ajax: {
        url:        route('models.propertySearch'),
        dataType:   'json',
        delay:      250,
        processResults: function(data) {
            return {
                results: data
            }
        }
    },
    placeholder:        'Enter property name',
    minimumInputLength: 1,
    multiple:           true,
    tags:               true,
    data:               initialPropertyOptions
});
<div>
    <label for="properties">Properties</label>
    <select name="properties[]" id="properties">
    </select>
</div>

An other simple way is set value to select option and make it select2 again :

$('#properties').val(["Trade Fair", "CA", "Party"]);
$('#properties').select2({});

It is working for me

改进不大:

$('#province').val(["3", "4", "5"]).trigger('change');