Select2 Default values for multiple select and allowed tags
Asked Answered
P

3

15

I have a select 2 multi-select option

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

I want to set some default values just in case the user is editing the form. I have successfully done that by doing this

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

But the problem is i am allowing user generated options using the tags: true option for select2.

When I set a default value that was initially in the html options it works, but when I set a default that was user generated it doesn't work.

It is my first time using select2.

How can i achieve this?

Paleethnology answered 20/6, 2016 at 7:54 Comment(1)
See this other answer here: https://mcmap.net/q/276665/-how-to-set-default-value-in-tagging-in-select2-jqueryLinis
L
21

Doing a little digging, I can see this issue raised on GitHub.

One option is to check to see if the value exists, and append it if it doesn't.

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>
Lifesaving answered 20/6, 2016 at 9:17 Comment(0)
H
2

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

Little improvement:

$('#province').val(["3", "4", "5"]).trigger('change');
Horseshoe answered 29/6, 2019 at 18:18 Comment(0)
C
1

I recently had to implement a select2 with options 'multiple' and 'tags' in a PHP script, and ran into a similar problem. The documentation said to add any initial selections as html option tags, but when I tried to add two, only one would show up in my select2 control.

I ended up initializing the select2 control with the config object 'data' option, which I would create dynamically.

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>
Comatose answered 1/12, 2017 at 22:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.