I'm getting a ajax response from my codeigniter controller and I'm setting that values in drop-down list box.
Here is my code:
<div class="form-group">
<label for="cluster_id"><span style="color:red;">*</span>Property Cluster</label>
<input type="hidden" name="cluster_id_property" id="cluster_id_property" value="<?= $addEditProperty->cluster_id; ?>">
<select class="form-control" id="cluster_id" name="cluster_id" required="">
<option value="">Select Cluster</option>
</select>
</div>
Here is my JS Code:
var cluster_id_property = document.getElementById('cluster_id_property').value;
var area_id = document.getElementById('area_id').value;
$.ajax({
'url' : '<?= base_url('property/clusterByArea'); ?>',
'type' : 'POST',
'dataType': 'JSON',
'data' : {area_id : area_id},
success : function(response) {
$('#cluster_id').find('option').not(':first').remove();
$.each(response,function(index,data){
$('#cluster_id').append('<option value="'+data['cluster_id_primary']+'">'+data['cluster_name']+'</option>');
});
}
});
My question is how I can set selected value in ajax response ? I want to show selected value in edit page
.
Any kind of help is welcome, thanks in advance.
You can easily compare the relevant variables and add an extra selected
attribute to the option string whenever they match. Just add an extra clause into the string you create within the append statement:
$('#cluster_id').append('<option value="'+data['cluster_id_primary']+'" '+ (area_id == data['cluster_id_primary'] ? ' selected ' : '') +'>'+data['cluster_name']+'</option>');