Can't set multiple values in Select2

痴心易碎 提交于 2019-12-17 18:56:40

问题


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.


回答1:


http://ivaynberg.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);



回答2:


Select2 4.0 version in case someone needs:

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



回答3:


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



回答4:


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


来源:https://stackoverflow.com/questions/24905607/cant-set-multiple-values-in-select2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!