Can't pre-select options in Select2 multiple choice select box
Alternatively, you can change the input
tag to select
. It seems to work below:
jQuery(document).ready(function() {
const acceArray2 = [{
id: 0,
text: "textA"
}, {
id: 1,
text: "textB"
}, {
id: 2,
text: "textC"
}];
jQuery("#accessories").select2({
data: acceArray2,
multiple: true,
placeholder: "",
width: 200
});
jQuery("#accessories").val("1");
jQuery("#accessories").trigger("change");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/select2.min.css" rel="stylesheet" />
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/select2.min.js"></script>
<select id="accessories"></select>