How to pre-select values in select2 multi select?
Asked Answered
B

6

18

I am having a multiple select like this:

<select multiple="multiple" class="myList">
        <option value="1" selected="selected">Apple</option>
        <option value="2" selected="selected">Mango</option>
        <option value="3" selected="selected">Orange</option>
</select>

Now, apart from those options which must come selected in the select box, I wanted additional ajax functionality which would give values from a remote source.

Here is my code for select2

$(function(){
    $(".myList").each(function(){

                $(this).select2({
                placeholder: "Search for fruits",
                minimumInputLength: 2,
                multiple: true,
                id: function(e) { 
                return e.id+":"+e.name; },
                ajax: {
                    url: "https://localhost:8443/fruit_search",
                    dataType: 'json',
                    data: function(term, page) {
                        return {
                            q: term
                        };
                    },
                    results: function(data, page) {
                    var frts=[];
                        $.each(data,function(idx,Frt){
                            frts[frts.length]=Frt;
                        });
                        return {
                            results: frts
                        };
                    }
                },
                initSelection: function(element, callback) {
                    var data = [];
                },
                formatResult: formatResult,
                formatSelection: formatSelection
                });
        });

});

But I am getting the error:

Error: Option 'id' is not allowed for Select2 when attached to a <select> element.

But when I use <input type="hidden"> then where should I keep the pre-selected options? How do I show them up when the select2 box appears?

Budworth answered 4/11, 2014 at 7:56 Comment(0)
R
16

If you only have values then you can use 'val' to get pre-selected values like this.

var PRESELECTED_FRUITS = [ '1','2','3'];

$('.myList').select2({}).select2('val', PRESELECTED_FRUITS);  
Radon answered 10/9, 2015 at 15:58 Comment(2)
I'm trying to use it but it's not working for me, jsfiddle.net/wzshpjb1 For me only one value is getting pre populated, I'm using select2 v4.0.6Felsite
@VishalB You need to trigger the change event. Something like $('selector').select2(); $('selector').val(['1', '2', '3']).trigger('change');Elison
A
9

You can use the "data" function to set the initial values:

var PRESELECTED_FRUITS = [
    { id: '1', text: 'Apple' },
    { id: '2', text: 'Mango' },
    { id: '3', text: 'Orange' }
];

$('.myList').select2('data', PRESELECTED_FRUITS)

Note: The "val" function is another way to set the initial values, but you only specify the ids with that function. In that case you would have to supply an "initSelection" function that builds the objects from the ids.

Also note that the "id" option is not the only option that is forcing you to use a hidden input. You cannot use the "ajax" option with a select element either.

As for the "id" option, I don't think you need it. Just put logic in the ajax "results" function so it builds an array of objects that have the proper id and text properties, or have the server return objects with those properties.

jsfiddle demo

Anyways answered 6/11, 2014 at 6:10 Comment(2)
Just a question, what happens if 'PRESELECTED_FRUITS' is empty? Will it produce an error? Or will select2 not load anymore?Heap
I figured out that it will not produce an error. it should still load regularly.Heap
O
5

To preset values use the 'val' property to preset the selected values.

$(this).select2({
            val: ["1","2","3"]
    }

But why not remove the 'id' function? If possible you could return the correct 'id' from the server without the need of the id function.

Offprint answered 5/11, 2014 at 22:41 Comment(0)
G
3

You can also load the values into the HTML:

<select class="selector" multiple="multiple" >
    <option selected value="1">Apple</option>
    <option selected value="2">Mango</option>
    <option selected value="3">Orange</option>
</select>

And connect select2 to it:

$(".selector").select2({
    width: 'inherit',
    minimumInputLength: 2,
    minimumResultsForSearch: 10,
    placeholder: "Search for fruits",
    ajax: {
        delay: 1000,
        url: "/bla_foo",
        dataType: 'json',
        type: "GET",
    }
})

and select2 will prefill the form.

Grimbald answered 4/7, 2019 at 13:30 Comment(0)
O
2
$('select').select2({
    multiple: true,
    data: [
        {id: 1, text: 'Foo', selected: true},
        {id: 2, text: 'Bar', selected: true}
    ]
})
Operose answered 14/3, 2022 at 14:30 Comment(0)
C
0
$("#select2").select2('data', {id: '3', text: 'myText'});
Consubstantial answered 6/10, 2019 at 8:16 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.