gpt4 book ai didi

javascript - 将所选值(来自数据库的值)设置为在ajax响应中的下拉列表中选择的值

转载 作者:行者123 更新时间:2023-12-03 00:54:37 24 4
gpt4 key购买 nike

我从 codeigniter Controller 收到 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响应中设置选定的值?我想在编辑页面中显示所选值。

欢迎任何形式的帮助,提前致谢。

最佳答案

您可以轻松比较相关变量,并在它们匹配时向选项字符串添加额外的 selected 属性。只需在附加语句中创建的字符串中添加一个额外的子句即可:

$('#cluster_id').append('<option value="'+data['cluster_id_primary']+'" '+ (area_id == data['cluster_id_primary'] ? ' selected ' : '') +'>'+data['cluster_name']+'</option>');

关于javascript - 将所选值(来自数据库的值)设置为在ajax响应中的下拉列表中选择的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52890578/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com