如何用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
相关产品推荐
相关产品推荐

