如何通过单个radio button绑定选中两个input输入框 基于Bootstrap实现
现有代码问题
- 所有input元素id重复,违反HTML规范,label的for属性也无法正确绑定目标元素
- 原生HTML本身不支持单个label同时选中多个表单元素,需要加少量JS实现需求
实现方案
你可以隐藏不需要直接展示的两个业务单选框,只给用户展示统一的可点击单选按钮,点击时同步给同组两个业务单选框设选中状态即可,修正后代码如下:
<!-- Twitter-Bootstrap --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous"> <!-- Body --> <div class="form-check form-check-inline"> <!-- 给用户点击的展示用单选框 --> <input class="form-check-input group-trigger" type="radio" name="showGroup" id="showRadio1" value="1"> <!-- 实际需要提交的两个隐藏单选框 --> <input class="d-none group-bind1" type="radio" name="name1" value="valu1"> <input class="d-none group-bind2" type="radio" name="name2" value="valu2"> <label class="form-check-label" for="showRadio1">1</label> </div> <div class="form-check form-check-inline"> <input class="form-check-input group-trigger" type="radio" name="showGroup" id="showRadio2" value="2"> <input class="d-none group-bind1" type="radio" name="name1" value="val8"> <input class="d-none group-bind2" type="radio" name="name2" value="val12"> <label class="form-check-label" for="showRadio2">2</label> </div> <div class="form-check form-check-inline"> <input class="form-check-input group-trigger" type="radio" name="showGroup" id="showRadio3" value="3"> <input class="d-none group-bind1" type="radio" name="name1" value="valu78"> <input class="d-none group-bind2" type="radio" name="name2" value="890"> <label class="form-check-label" for="showRadio3">3</label> </div> <script> // 监听所有展示用单选框的变更事件 document.querySelectorAll('.group-trigger').forEach(trigger => { trigger.addEventListener('change', function() { if (this.checked) { // 先清空两组业务单选框的选中状态 document.querySelectorAll('.group-bind1').forEach(el => el.checked = false) document.querySelectorAll('.group-bind2').forEach(el => el.checked = false) // 选中当前分组的两个业务单选框 const parentEl = this.parentElement parentEl.querySelector('.group-bind1').checked = true parentEl.querySelector('.group-bind2').checked = true } }) }) </script>
逻辑说明
- 用Bootstrap自带的
d-none类隐藏不需要用户直接操作的业务单选框,只保留统一的单选入口,交互和原生单选完全一致 - 代码完全兼容动态生成的选项,只要保持类名、结构一致即可正常生效
- 表单提交时可以正常拿到
name1和name2两个参数的对应选中值,不需要额外处理
内容的提问来源于stack exchange,提问作者spiritman
相关产品推荐
相关产品推荐

