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.

1

11 Answers 11

19

right solution in version 4.x by example:

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

see: Creator description

0
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);
1
  • 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 object Jan 22, 2014 at 8:56
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");
5
  • 1
    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 control
    – M Rajoy
    Apr 22, 2013 at 9:00
  • 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?).
    – user504674
    Apr 22, 2013 at 9:05
  • 1
    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.
    – M Rajoy
    Apr 22, 2013 at 9:19
  • So when exactly would you like to select a value in the selectbox?
    – user504674
    Apr 22, 2013 at 9:50
  • 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.
    – M Rajoy
    Apr 22, 2013 at 9:53
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>
5
  • Unfortunately, that doesn't work! The items show up in the box with no text!
    – Triynko
    Mar 7, 2016 at 22:30
  • Worked like a charm for me (not using ajax source)
    – Roland
    Jun 9, 2016 at 9:48
  • 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? Sep 20, 2016 at 8:55
  • +1 @Triynko 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>
    – absin
    Mar 30, 2017 at 8:40
  • 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?
    – absin
    Mar 30, 2017 at 10:20
2

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

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

0

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

$('#el').data().select2.updateSelection(defaultData);
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

0

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?

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.

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
            }
        });
    });
}
-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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.