I'm trying to load selected values from db and set it on the select2. i'm using the select2 4.0.10 version. im loading the data using ajax and set the select option to the select2 element after the document is ready.
so, i tried using the $("#area").val(selectedValues).trigger("change"); but nothing seems to be selected.
here is some code of my view.
<input class="form-control" type="text" id="sourceValues" value="CMS,KDY,RWG">
here is my select2 element
<div class="form-group row">
<label class="col-md-3" for="area">Area Tagih Kolektor</label>
<div class="col-md-9">
<select id="area" class="js-example-basic-multiple form-control" name="area[]" multiple="multiple" required>
</select>
</div>
</div>
and here is my script for set the selected values.
<script>
$(document).ready(function(){
nav_active();
var selectedValues = ["CMS","KDY","RWG"];
$('.js-example-basic-multiple').select2({
placeholder: "Pilih Cabang Area Tagih Collector Agency...",
multiple: true
});
console.log(selectedValues);
//Date picker
$('#tgl_berlaku').datepicker({
autoclose: true
})
//Prevent enter to submit
$(window).keydown(function(event){
if(event.keyCode == 13) {
event.preventDefault();
alertify.error('Untuk melakukan submit form, tekan tombol "Simpan"!');
return false;
}
});
$.ajax({
url: "<?php echo base_url();?>ama/c_agency/populate_dropdown_cabang",
type: 'GET',
success: function(data) {
var html = '';
var j;
data = JSON.parse(data);
for(j=0; j<data.length; j++){
html += '<option value="'+data[j].GroupBranchID+'">'+data[j].branch+'</option>';
}
var posisi = "#area";
$(posisi).append(html);
}
});
$("#area").val(selectedValues).trigger("change");
});
function nav_active(){
var d = document.getElementById("nav-ama-agency");
d.className = d.className + "active";
}
</script>
there is no error when im running the script.
You need to change the way you are appending options to Select Box in your ajax success callback.
Instead of following way to append options.
data = JSON.parse(data);
for(j=0; j<data.length; j++){
html += '<option value="'+data[j].GroupBranchID+'">'+data[j].branch+'</option>';
}
You need to append options using the following method
for(j=0; j<data.length; j++){
var option = new Option(data[j].branch, data[j].GroupBranchID );
$("#area").append(option);
}
Document states that
New options can be added to a Select2 control programmatically by creating a new Javascript Option object and appending it to the control:
Here is the JS Fiddle which adds New Option to Select Box on a Click Event. In your case, Click Event fires an AJAX Call and remotely fetches data.