问题
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