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

标签 javascript ajax drop-down-menu codeigniter-3 selectedvalue

我从 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/

相关文章:

javascript - Emacs命令将JS对象转换为JSON

javascript - 在内存中可视化的对象结构

javascript - PHP - 获取数据时 Ajax 自动刷新页面

html - 自定义下拉列表箭头

javascript - 如何根据先前选择的下拉列表值(比另一个下拉列表更大)禁用下拉选项

javascript - 在打开时更改下拉列表的内容?

JavaScript 重定向不起作用

javascript - iframe 中的页面宽度

javascript - 提交表单后如何隐藏表单

java - 接收 UTF-8 时,REST 会忽略非英文字符的任何部分