select2: default selection in multiple select with AJAX
Asked Answered
M

11

25

I am using the awesome select2 to create a multiple selection combo.

I would like to programmatically select default values (as in selections the user has made previously), but I don't know how. I read that using initSelection does the trick but this is called when creating the combo and I don't want this default selection to be always done.

Merc answered 22/4, 2013 at 8:47 Comment(1)
have you found the answer?Trek
P
19

right solution in version 4.x by example:

$('#element').val(['val1','val2']).trigger('change');

see: Creator description

Pearson answered 18/12, 2016 at 7:49 Comment(0)
Q
7

I found some solutions, maybe that will help you:

$('#el').select2({...}) // init select2

var defaultData = [{id:1, text:'Item1'},{id:2,text:'Item2'},{id:3,text:'Item3'}];

$('#el').data().select2.updateSelection(defaultData);
Quiroz answered 22/5, 2013 at 14:22 Comment(1)
this above code was working okay for me, but ran into some issues when troubleshooting. for the life of me couldn't find documentation on .updateSelection(). also i would get a weird line break when in the input when preloading data. found some new code that worked better for me. $('#input').select2('data', preload_data); where preload_data is objectBancroft
M
3

From the documentation page:

"val - Gets or sets the selection. If the value parameter is not specified, the id attribute of the currently selected element is returned. If the value parameter is specified it will become the current selection."

Also, from the docs:

$("#e8").select2("val", "CA");
Mcgough answered 22/4, 2013 at 8:59 Comment(5)
That won't work. Since the data is loaded dynamically via AJAX, when you set the val property there are simply no elements loaded to the controlMerc
After your ajax call has completed, and you have set the data into the selectbox, THEN from within the ajax call success handler, you can call the code mentioned in the answer above? That is if you are using your own Ajax call. But if you're using the Ajax call provided by the component, I don't know - it doesn't offer a completion hook event - so you might as well write your own (10 lines maybe?).Mcgough
That wouldn't work because my AJAX call is based on the search term the user has typed in the input (so it won't be loading the whole set of elements). Also, I don't want my selection to be shown at all times; I would like to be able to switch it on an off.Merc
So when exactly would you like to select a value in the selectbox?Mcgough
I've got this two buttons that show my form, one should show the form with the elements selected, the other one should show it clean.Merc
S
3

As outlined in the documentation here, you can simply add 'options' to your select markup to have initial default values preselected.

<select class="js-data-example-ajax">
  <option value="3620194" selected="selected">select2/select2</option>
</select>
Shirring answered 25/1, 2016 at 18:7 Comment(5)
Unfortunately, that doesn't work! The items show up in the box with no text!Delve
Worked like a charm for me (not using ajax source)Hagiology
I have the same behavior as @Triynko. I added one option to the select markup and initialized select2 with ajax source afterwards with the result that the select field stays blank. Any ideas?Praseodymium
+1 @Delve same think happening with me. Did you figure out a fix?? I am trying to now port the initial data as json rather than giving it in DOM as <option>Disinfect
Figured it out finally, no need to supply the json!! The inner html of the <option> is put into the repo object under the text key. So repo.text will give the innerhtml. That is, all we have to do is supply repo.text to the formatSelection option. Also the json being passed from the servlet (controller) should have the desired label text put under the text key!! Still figuring out how to add attributes to the li elements created, so that I can save the changed list. Any ideas?Disinfect
S
2

$('#el').select2().val(['val1','val2']).trigger("change")

does the trick but for some reasons it removes the ability to add your own tag...

Sela answered 9/8, 2016 at 17:46 Comment(0)
D
1

Figured it out finally!! Select2 iterates through the <option> tag under the <select>.

<select class="js-data-example-ajax" style="width:100%">
  <option value="3620194" selected="selected">Put the pre-selected options here</option>
</select>

The inner html of the <option> is put into the repo object under the text key. So repo.text will give the innerhtml. That is, all we have to do is supply repo.text to the formatSelection option in the init. Also the json being passed from the servlet (controller) should have the desired label text put under the text key!! Still figuring out how to add attributes to the li elements created, so that I can save the changed list. Any ideas?

Disinfect answered 30/3, 2017 at 10:26 Comment(0)
T
0

The following code works fine, but the select2 need to be refreshed

$('#el').data().select2.updateSelection(defaultData);
Trumpetweed answered 13/1, 2014 at 11:56 Comment(0)
I
0

To extend on @sanj answer. This seem to be working for me in my projects.

Via HTML

HTML

<select class="select2" style='width:100%;' multiple>
    <option val=''>Please choose</option>
    <option val="1" selected>One</option>
    <option val="2" selected>Two</option>
    <option val="3">Three</option>
</select>

JS

$('.select2').select2();

Results enter image description here

Via Javascript

HTML

<select class="select2" style='width:100%;' multiple>
    <option val=''>Please choose</option>
    <option val="1">One</option>
    <option val="2">Two</option>
    <option val="3">Three</option>
</select>

JS

$('.select2').select2();
var defaultData = [{id:1, text:'One'},{id:2,text:'Two'}];
$('.select2').data().select2.updateSelection(defaultData);

Results enter image description here

Interleave answered 8/11, 2016 at 10:40 Comment(0)
L
0

I looped through an array of values, Then set each option that matched to ("selected",true)

values = [2, 5, 3]

for val in values
  $("#selects_id option[value="+val+"]").prop("selected",true).trigger("change")

You can also do with the results you get from an Ajax call.

Literalism answered 12/12, 2017 at 18:12 Comment(0)
E
0

<select class="form-control" id="selectid" name="selectid"></select>

$('#selectid').select2({
placeholder: 'Please Search with ID',
ajax: {
url: '/getData.php',
dataType: 'json',
delay: 250,
processResults: function (data) {
    return {
        results: data
    };
},
cache: true
}
});
var id    = "idvalue";
var text  = "Text String";
if(id !== null && id !== ''){
    var studentSelect = $('#selectid');
    $.ajax({
        type: 'GET',
        url: '/getData.php'
    }).then(function (data) {
        var option = new Option(id, text, true, true);
        studentSelect.append(option).trigger('change');
        studentSelect.trigger({
            type: 'select2:select',
            params: {
                data: data
            }
        });
    });
}
Ewald answered 9/7, 2021 at 14:36 Comment(0)
D
-1

You can find a solution here with An auto complete, multiple selection Drop-down list using JQuery Select2.

Binds data with an HTML "select" element which is then taken over by "Select2" functions to convert it into a beautiful multi-select drop-down list.

It might perform well using AJax and will sure try in the coming days.

Dorso answered 14/7, 2013 at 6:0 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.