点击提交按钮后如何保持Radio Button的选中状态?
解决单选按钮页面刷新后选中状态丢失的问题
先指出你现有代码里的两个明显问题:
- JavaScript中的
reportfrom变量未定义,没有来源渠道获取选中值 sip01分支里错误选中了reportfrom2,应该对应reportfrom3
要保持单选按钮的选中状态,最常用的方案是利用**浏览器本地存储(localStorage)**保存用户选择,页面刷新后读取存储值恢复状态。以下是修改后的完整代码:
修改后的HTML代码
<div class="form-group"> <div class="form-check form-check-inline"> <input class="form-check-input" type="radio" name="reportfrom" id="reportfrom1" value="ucgw"> <label class="form-check-label" for="reportfromucgw1">UCGW1</label> </div> <div class="form-check form-check-inline"> <input class="form-check-input" type="radio" name="reportfrom" id="reportfrom2" value="ucgw2"> <label class="form-check-label" for="reportfromucgw2">UCGW2</label> </div> <div class="form-check form-check-inline"> <input class="form-check-input" type="radio" name="reportfrom" id="reportfrom3" value="sip01"> <label class="form-check-label" for="reportfromsip01">SIP01</label> </div> </div> <div class="form-group"> <input type="submit" class="btn btn-info" value="Hentam!" onclick="test()"/> </div>
修改后的JavaScript代码
<script> // 页面加载时自动恢复选中状态 window.onload = function() { const savedValue = localStorage.getItem('selectedReportFrom'); if (savedValue) { const targetRadio = document.querySelector(`input[name="reportfrom"][value="${savedValue}"]`); if (targetRadio) targetRadio.checked = true; } }; function test() { // 获取当前选中的单选框值 const selectedRadio = document.querySelector('input[name="reportfrom"]:checked'); if (selectedRadio) { localStorage.setItem('selectedReportFrom', selectedRadio.value); // 这里可以添加你的其他业务逻辑,比如表单提交操作 } } </script>
逻辑说明
- 点击提交按钮时,
test()函数会捕获用户选中的单选框值,存入localStorage(该存储会持久保存在浏览器中,除非手动清除) - 页面加载完成后,自动从
localStorage读取保存的值,找到对应单选框并设置为选中状态
如果你的场景是表单提交到后端,也可以让后端将用户选中的值返回前端,在页面渲染时直接给对应单选框添加checked属性。比如后端返回reportfrom=ucgw,HTML可写为:
<input class="form-check-input" type="radio" name="reportfrom" id="reportfrom1" value="ucgw" checked>
内容的提问来源于stack exchange,提问作者CurlyBoi
相关产品推荐
相关产品推荐

