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

如何用Laravel Blade实现单选框默认选中及提交后回显保持选中

问题原因

你给value="no"的单选框硬编码了checked属性,该属性优先级高于Blade的条件判断,会导致无论old()是否存在提交后的用户选择值,No选项始终处于选中状态,回显逻辑失效。

修复方案

去掉硬编码的checked属性,利用Laravel old()辅助函数的第二个参数设置默认值即可:old('参数名', 默认值),当没有提交记录时会自动返回第二个参数作为默认值,有提交记录时优先返回用户提交的值,同时满足默认选中和提交后回显的需求。

修正后完整代码

<label for="no" class="col form-check-label">No</label>
<input type="radio" name="visualCheck" value="no" id="no" class="col p-0 m-0" style="display:inline-block;vertical-align:middle;"  @if(old('visualCheck', 'no') == 'no') checked @endif />

<label for="yes" class="col form-check-label">Yes</label>
<input type="radio" name="visualCheck" value="yes" id="yes" class="col" style="display:inline-block;vertical-align:middle;" @if(old('visualCheck', 'no') == 'yes') checked @endif />

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 21:36:04