Reputation: 335
I'm trying to load an array of selected items into an existing select2 dropdown, so that there are pre-selected items on load, but i'm struggling to get my syntax correct.
Give the following json array, which is $scope.attributes
[{"AttributeId":169,"AttributeName":"Abstract"},
{"AttributeId":170,"AttributeName":"Animal"},
{"AttributeId":171,"AttributeName":"Beach"}]
and the initial code to create a select2 dropdown
$(".attribute-tagging").select2({
closeOnSelect: true, placeholder: ""
});
and the html tag for the dropdown which loads all available options.
<select class="attribute-tagging" id="edit-attributes" multiple="multiple">
<option value="{{attribute.AttributeId}}" ng-repeat="attribute in attributes">{{attribute.AttributeName}}</option>
</select>
This works, but I'd like to have 1 or more of these items already selected, so that on page load, all attributes are added into the select list, and then, for example - Animal and Beach are already selected.
Ideally an array I can populate which when passed into the select2 dropdown marks some of the items in the list as 'selected'.
So, in a nutshell
Any help would be greatly appreciated.
Upvotes: 0
Views: 8715
Reputation: 726
You can select multiples by using id
$('#edit-attributes').val(["169", "171"]);
$('#edit-attributes').trigger("change");
Not forgot to trigger change event at the end !!!
Upvotes: 1
Reputation: 914
Try this code.
var $mySelect = $(".attribute-tagging").select2({
closeOnSelect: true, placeholder: ""
});
$mySelect.val(["169", "171"]).trigger("change");
Now Abstract and Beach are selected
Upvotes: 3