My HTML code is:
<select id="block-permissions" name="permissions" multiple="multiple">
{{-- <option value="0">Topic 0</option> When uncomment works fine! --}}
</select>
My JS code is:
$(function() {
// const permissions = @json($permissions)
//
const permissions = {
results: [{
text: "Group 1",
children: [{
id: 1,
text: "Topic 1",
selected: true
},
{
id: 2,
text: "Topic 2",
selected: true
},
{
id: 3,
text: "Topic 3",
selected: false
}
]
}]
}
$('#block-permissions').select2({
data: permissions,
})
})
Select2 control works only with Topic 0 (predefined HTML data), but completely ignores JS data.
What's wrong?
I had to modify what was in the documentation to remove the "results" key and set your object like the following:
const permissions = [{
text: "Group1",
children: [{
id: "1",
text: "Option 1",
selected: true
},
{
id: "2",
text: "Option 2",
selected: true
}
]
},
{
text: "Group2",
children: [{
id: "3",
text: "Option 3",
selected: true
},
{
id: "4",
text: "Option 4",
selected: false
}
]
}
];
Here is a working code snippet:
$(function() {
const permissions = [{
text: "Group1",
children: [{
id: "1",
text: "Option 1",
selected: true
},
{
id: "2",
text: "Option 2",
selected: true
}
]
},
{
text: "Group2",
children: [{
id: "3",
text: "Option 3",
selected: true
},
{
id: "4",
text: "Option 4",
selected: false
}
]
}
];
$('#block-permissions').select2({
placeholder: 'Select one or more',
data: permissions
});
});
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/css/select2.min.css" integrity="sha512-nMNlpuaDPrqlEls3IX/Q56H36qvBASwb3ipuo3MxeWbsQB1881ox0cRv7UPTgBlriqoynt35KjEwgGUeUXIPnw==" crossorigin="anonymous" referrerpolicy="no-referrer" />
<select style="min-width:25%;width:25%;" id="block-permissions" name="permissions" multiple="multiple">
</select>
<script
src="https://code.jquery.com/jquery-3.7.1.js"
integrity="sha256-eKhayi8LEQwp4NKxN+CfCh+3qOVUtJn3QNZ0TciWLP4="
crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/js/select2.min.js" integrity="sha512-2ImtlRlf2VVmiGZsjm9bEyhjGW4dU7B6TNwh/hx/iSByxNENtj3WVE6o/9Lj4TJeVXPi4bnOIMXFIJJAeufa0A==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>