I am using the same form for adding new product and editing product with id. When we add a new product, its categories are selected from the select2 dropdown. But when we edit the already existing product, I want to display its category as default option. I tried with initSelection but in this way only text is displayed and its value is undefined. My form HTML code is:
<form class="form-horizontal form-label-left" novalidate>
<div class="item form-group">
<label class="control-label col-md-3 col-sm-3 col-xs-12" >Category
</label>
<div class="col-md-6 col-sm-6 col-xs-12">
<select class="select2_single form-control col-md-7 col-xs-12" ></select>
</div>
</div>
<div class="item form-group">
<label class="control-label col-md-3 col-sm-3 col-xs-12" >Name <span class="required">*</span>
</label>
<div class="col-md-6 col-sm-6 col-xs-12">
<input id="name" class="form-control col-md-7 col-xs-12" value="<?php echo $name; ?>" placeholder="Product Name" required="required" type="text">
</div>
</div>
</form>
and my jquery script is
<script>
$(document).ready(function () {
categories();
});
function categories() {
$.ajax({
'url' : 'category/data',
'success' : function(data){
var j = $.parseJSON(data);
var select2_ary = [];
$.each(j, function(k, v) {
select2_ary.push({
id : v['id'],
text : v['category']
});
});
var id = "<?php echo $id; ?>";
if(id != '') {
$(".select2_single").select2({
placeholder: "Select a Category",
initSelection: function(element, callback) {
callback({val: '3223', text: '<?php echo $id; ?>' });
},
data : select2_ary
});
}
else {
$(".select2_single").select2({
placeholder: "Select a Category",
data : select2_ary
});
}
}
});
}
</script>
I'm not sure about about the select2 version but its not the latest one. When I submit this form, I am not getting the value of select2 default option. Please help!