我是javascript的初学者。我有一个依赖下拉列表,我的问题是当有人在编辑时,在依赖下拉列表中,编辑下拉菜单不会自动选择。这是我的表单代码:
<div class="form-group">
<label class="control-label col-md-3 col-sm-3 col-xs-12" for="prov_id">Provinsi
</label>
<div class="col-md-6 col-sm-6 col-xs-12">
<?php
$additional_dd_code = 'id="reg_province" class="select2_single form-control col-md-7 col-xs-12" tabindex="-1"';
echo form_dropdown('prov_id', $prov_options, $prov_id, $additional_dd_code);
?>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3 col-sm-3 col-xs-12" for="city_id">Kota/Kabupaten
</label>
<div class="col-md-6 col-sm-6 col-xs-12">
<select name="city_id" id="reg_city" class="select2_single form-control col-md-7 col-xs-12" tabindex="-1" >
<option value=""></option>
</select>
</div>
</div>
这是我的javascript:
$(document).ready(function () {
$('#reg_province').change(function () {
var prov_id = $('#reg_province').val();
if (prov_id != '') {
$.ajax({
url: "<?= base_url() ?>reg_city/fetch_city",
method: "POST",
data: {prov_id: prov_id},
success: function (data) {
$('#reg_city').html(data);
}
})
}
})
})
这是我用于更新依赖下拉列表的控制器:
function fetch_city() {
$prov_id = $this->input->post('prov_id', TRUE);
if ($prov_id == TRUE) {
$query = $this->get_where_custom_order_by('prov_id', $prov_id, 'city_name');
foreach ($query->result() as $item) {
echo '<option value="'.$item->city_id.'">'.$item->city_name.'</option>>';
}
}
}
在依赖下拉列表中,我遇到的唯一问题是编辑时。它应该显示选定的 ID。但实际上,它没有显示任何数据。那么,我的代码应该如何?
对默认值执行此操作
// in this handler
success: function (data) {
$('#reg_city').html(data);
// add below line
if(city_id){
$('#reg_city').val(city_id);
}
}