Can't set multiple values in Select2
Asked Answered
I

6

12

I am trying to show selected values in select2-jquery component.

var select = $(".select2").select2({
    multiple: true,
    placeholder: "",
    width:'100%',
    data: z 
});
var selectedValues = $("#sourceValues").val().split(',');

$.each( selectedValues, function(k,v){
    $(".select2").select2('val',v);
})

Element sourceValues holds the value e.g : 2,4 And z is array of object that holds id and text as suggested. I can see the <options> that is linked to the Select2 element but I am unable to show the selected values on the element. Also, If I try to run the query on Chrome console it works , if I write something like ;

  $(".select2").select2('val',4) 

Hence, the <option> with the id 4 is selected.

Incontestable answered 23/7, 2014 at 8:36 Comment(1)
Have you tried to set the array directly: $(".select2").select2('val', selectedValues);?Cataclinal
A
16

Update (Select2 4.0+)

Since version 4.0, you should use .val(...) followed by trigger('change') from jQuery.

https://select2.org/programmatic-control/add-select-clear-items#selecting-options

Up-to-date example:

var selectedValues = $("#sourceValues").val().split(',');
$(".select2").val(selectedValues).trigger('change');

// $(".select2").val([1, 2]).trigger('change');

Original answer (Select2 3.5.3)

http://select2.github.io/select2/#documentation

val

Attached to select - Multi-Valued - Array of the value attributes of the options that should be selected. null for empty.

So:

var selectedValues = $("#sourceValues").val().split(',');
$(".select2").select2('val',selectedValues);

// $(".select2").select2('val',[1, 2]);
Autolysis answered 24/7, 2014 at 7:53 Comment(2)
this seems to be not working on multiple select or I am missing something.Honeydew
For 4.0.2 $('.select2').val(selectedValues); seems to be workingBrunildabruning
S
42

Select2 4.0 version in case someone needs:

var selectedValues = $("#sourceValues").val().split(',');
$(".select2").val(selectedValues).trigger("change");
Stopping answered 25/11, 2015 at 8:52 Comment(3)
Thank you sir. I've been googling for more than an hour! :DFart
OMG I have been racking my brains trying every possible solution I could find with no avail and this did it, thanks so much man! It was all about .val().split(',');Fifteenth
This should be changed to the accepted answer as evidenced by the upvotes. Thank you.Gunn
A
16

Update (Select2 4.0+)

Since version 4.0, you should use .val(...) followed by trigger('change') from jQuery.

https://select2.org/programmatic-control/add-select-clear-items#selecting-options

Up-to-date example:

var selectedValues = $("#sourceValues").val().split(',');
$(".select2").val(selectedValues).trigger('change');

// $(".select2").val([1, 2]).trigger('change');

Original answer (Select2 3.5.3)

http://select2.github.io/select2/#documentation

val

Attached to select - Multi-Valued - Array of the value attributes of the options that should be selected. null for empty.

So:

var selectedValues = $("#sourceValues").val().split(',');
$(".select2").select2('val',selectedValues);

// $(".select2").select2('val',[1, 2]);
Autolysis answered 24/7, 2014 at 7:53 Comment(2)
this seems to be not working on multiple select or I am missing something.Honeydew
For 4.0.2 $('.select2').val(selectedValues); seems to be workingBrunildabruning
Q
5
var selectedValues = $("#sourceValues").val().split(',');
var $multiSelect = $(".select2").select2();
$multiSelect.val(selectedValues).trigger("change");
Quinsy answered 31/8, 2016 at 12:40 Comment(0)
S
0

for create dynamic array for example in a loop do like this:

 data=[]

    for(let input of inputs){

          *//key of dynamic build*
           if(typeof data[input.name]==='undefined'){
                data[input.name]=[]}
            data[input.name].push(input.value);
            console.log(data)
        }
Superheat answered 24/12, 2018 at 13:29 Comment(0)
M
0

Hey I find and a bit upgrade and use ŁukaszW.pl suggestion for JavaScript/jQuery set values selection in a multiple select and you can use it as well:

in jQuery:

var values = ["Test", "Prof", "Off"]; // or to take values as array from other document element;
$("#strings").val(values);
$("#strings").trigger('change'); //trigger change for select2 to set values/styles

or in pure JavaScript:

var element = document.getElementById('strings');
var values = ["Test", "Prof", "Off"]; // or to take values as array from other document element;
for (var i = 0; i < element.options.length; i++) {
    element.options[i].selected = values.indexOf(element.options[i].value) >= 0;
}
var event = new Event('change'); 
var sel = document.getElementById("strings"); 
sel.dispatchEvent(event); //trigger change for select2 to set values/styles

jQuery does significant abstraction here.

and Save :) Hope it helps someone :)

Maneating answered 15/1, 2020 at 12:26 Comment(0)
S
0

given:

  1. select2 v4
  2. "Options" gets a php script when drawing a page from the database

it is necessary that select2 is filled as in the database. by default, it renders like this: option value description

I solved the question like this: from class "select2-searchable" i am incluted html atrrribute <data-reorder="1"> and <data-value="a,d,c"> (from php)

$('.select2-searchable').each(function(i, e) { //table, interation all elements
    $(e).select2({
        minimumResultsForSearch: 1,
        width: 'resolve',
    });
    if ($(e).attr('data-reorder')) {
        $(e).on('select2:select', function(el) { //adding a new value to the end of the list
            $(this).append(el.params.data.element).trigger('change.select2');
        });
        if ($(e).attr('data-value')) { //sorting by values from the database
            $.each($(e).attr('data-value').split(','), function(j, k) {
                $(e).find('[value=' + k + ']').each(function(m, l) {
                    l.selected = true;
                    $(e).append(l).trigger('change');
                });
            });
        }
    }
});

example here (https://jsfiddle.net/M0rdent/q9gn305d/3/)

Strove answered 21/1, 2021 at 6:17 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.