I need to set an array of data after initializing select2. So I want to make something like this:
var select = $(\'#select\').select2({});
select.data([
{id: 1
I've recently had the scenario where changing one select2 object alters the contents of a second (parent - child groupings effectively). I used an ajax call to retrieve a new set of Json data, which was then picked up by the second select2 object. I've included the code below:
$("#group").on('change', function () {
var uri = "/Url/RetrieveNewResults";
$.ajax({
url: uri,
data: {
format: 'json',
Id: $("#group :selected").val()
},
type: "POST",
success: function (data) {
$("#groupchild").html('');
$("#groupchild").select2({
data: data,
theme: 'bootstrap',
placeholder: "Select a Type"
});
},
error: function () {
console.log("Error")
}
});
});
I found that I had to include the $("#groupchild").html('') in order to clear out the previous set of data in the second select2. Hope this helps.