[英]cant set selected value on select2 javascript ajax mode
i have a select2 element that load data from database using ajax.我有一个 select2 元素,它使用 ajax 从数据库加载数据。 i want to load the value from db and select it as selected value in edit mode.
我想从 db 和 select 加载值作为编辑模式下的选定值。 but im not able to load the value using trigger function.
但我无法使用触发器 function 加载值。
i tried using looping by comparing selected values but i got the select2 option orinted twice.我尝试通过比较选定的值来使用循环,但我得到了 select2 选项两次。
$(document).ready(function(){
var area = $('#area').select2({
placeholder: "Pilih Cabang Area Tagih Collector Agency...",
multiple: true,
allowClear: true,
width: 'resolve'
});
var k;
var selected = [];
//imloading the value from db and insert it into an array
<?php foreach($area_coll as $area){
?>
selected.push("<?php echo $area->group_branch_id;?>");
<?php
}?>
$.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);
//looping cabang
for(j=0; j<data.length; j++){
$('#area').append($('<option>').val(data[j].GroupBranchID).text(data[j].branch));
}
}
});
//this function not working at all
area.val(selected).trigger("change");
});
im not getting any error with this code nor the value still not selected.我没有收到此代码的任何错误,也没有选择该值。
Select2 have ajax options. Select2 有 ajax 选项。 So I think you can use ajax directly as an options of select2 (reference: https://select2.org/data-sources/ajax#default-pre-selected-values )
所以我认为您可以直接使用 ajax 作为 select2 的选项(参考: https://select2.org/data-sources/ajax#default-pre-selected-values )
The document said:文件说:
To provide default selections, you may include an <option> for each selection that contains the value and text that should be displayed:
<select class="js-example-data-ajax form-control">
<option value="3620194" selected="selected">select2/select2</option>
</select>
Mean that at the options you can push selected="selected"
at edit page when option is stored on exist record.意味着,在“存在的记录”上存储选项时,在选项上,您可以在编辑页面上
selected="selected"
。 Hope it help.希望它有所帮助。 thanks
谢谢
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.