Reputation: 173
I'm trying to pre populate selected options using 'val', but I'm getting only one option as preselected in the options. JSFiddle code
<select name="question_tags[]" id="question_tags" class="select2_tags" multiple="multiple">
$(document).ready(function() {
$('.select2_tags').select2({
placeholder:"Select",
data : ["Data Structure", "DBMS", "OS"]
}).select2('val', ["OS", "DBMS"]);
});
I'm using select2 v4.06
I explored it, and found the functionalities implemented for the previous version of select2, which is now deprecated in recent versions Existing solutions JSFiddle
The solution in the link is not working for current version of select2, How to pre-select values in select2 multi select?
Upvotes: 2
Views: 4532
Reputation: 23778
Above all you need to use multiple:true
option to make it multiselect, then you need to use SelectElement.val([1,2,3])
and then SelectElement.trigger('change')
to notify any JS Components about the value has changed. Docs
Reference
See demo below
$(document).ready(function() {
var select2 = $('.select2_tags').select2({
placeholder: "Select",
width: '500px',
data: ["Data Structure", "DBMS", "OS"],
multiple: true,
})
select2.val(["DBMS", "OS"]);
select2.trigger("change");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/js/select2.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/css/select2.min.css" rel="stylesheet" />
<select name="question_tags[]" id="question_tags" class="select2_tags" multiple="multiple">
</select>
Upvotes: 4