You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Codeigniter下拉选择框已保存值无法自动选中回显问题求助

问题修复方案

下拉选择框和文本输入框的回显逻辑存在差异:文本框只需给value属性赋值即可完成回显,下拉框需要为和存储值匹配的option项添加selected属性才能实现默认选中效果,你当前的代码没有加对应判断,所以编辑页加载时无法自动选中已保存的值。

你可以直接将下拉框的代码替换为以下内容即可实现正常回显:

<div class="col-md-3">
    <label>Condition</label> 
    <select data-placeholder="Choose Condition..." class=" select-search" tabindex="2"  name="condition">
        <option value=""></option>
        <option value="New" <?php if(isset($result['condition']) && $result['condition'] == 'New') echo 'selected';?>>New</option>
        <option value="Used" <?php if(isset($result['condition']) && $result['condition'] == 'Used') echo 'selected';?>>Used</option>
    </select>
</div>

如果想要兼容表单提交失败后保留上次选中值的场景,可以使用CodeIgniter自带的表单助手的set_select()方法,写法更规范:

<!-- 首先需要在控制器中加载表单助手 $this->load->helper('form'); -->
<option value="New" <?php echo set_select('condition', 'New', isset($result['condition']) && $result['condition'] == 'New');?>>New</option>
<option value="Used" <?php echo set_select('condition', 'Used', isset($result['condition']) && $result['condition'] == 'Used');?>>Used</option>

set_select()方法的第三个参数为布尔值,编辑页首次加载时会匹配数据库存储的值自动选中,表单提交校验失败刷新时会自动读取上一次提交的选中值,无需额外判断。

内容的提问来源于stack exchange,提问作者Kyle White

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 14:06:03