将所选值(来自数据库的值)设置为在 ajax 响应的下拉列表中选择
Set selected value (value from database) as selected in drop down in ajax response
我从我的 codeigniter 控制器收到 ajax 响应,我在下拉列表框中设置该值。
这是我的代码:
<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>
这是我的 JS 代码:
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>');
});
}
});
我的问题是如何在 ajax 响应中设置选定值?我想在 edit page
.
中显示选定的值
欢迎任何形式的帮助,在此先感谢。
您可以轻松比较相关变量,并在匹配时向选项字符串添加额外的 selected
属性。只需在附加语句中创建的字符串中添加一个额外的子句:
$('#cluster_id').append('<option value="'+data['cluster_id_primary']+'" '+ (area_id == data['cluster_id_primary'] ? ' selected ' : '') +'>'+data['cluster_name']+'</option>');
我从我的 codeigniter 控制器收到 ajax 响应,我在下拉列表框中设置该值。
这是我的代码:
<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>
这是我的 JS 代码:
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>');
});
}
});
我的问题是如何在 ajax 响应中设置选定值?我想在 edit page
.
欢迎任何形式的帮助,在此先感谢。
您可以轻松比较相关变量,并在匹配时向选项字符串添加额外的 selected
属性。只需在附加语句中创建的字符串中添加一个额外的子句:
$('#cluster_id').append('<option value="'+data['cluster_id_primary']+'" '+ (area_id == data['cluster_id_primary'] ? ' selected ' : '') +'>'+data['cluster_name']+'</option>');