根据前一组单选框选择结果禁用后一组同色单选框,现有代码不生效
问题修复方案
原有代码无法生效的核心原因是第一组单选框没有绑定选中触发事件,导致你写的校验逻辑从未执行,具体修复如下:
修复说明
- 给所有name为
main的单选框添加onchange事件,选中时触发校验逻辑 - 修正HTML中重复的id值(id必须全局唯一,将两组颜色容器的id分别改为
showchartcolor_main和showchartcolor_other) - 优化JS逻辑:如果第二组已经选中了和第一组相同的颜色,同步清除该选项的选中状态,避免提交异常
修复后的完整代码
HTML代码
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css" rel="stylesheet"> <div class="card"> <div class="card-body"> <label> Color 1</label> <div id="showchartcolor_main"> <div class="showchartcolor"> <label for="pink_main"> <i style="font-size: 48px; color: #ff829d;" class="fa fa-square"></i></label> <input type="radio" id="pink_main" name="main" value="#ff829d" onchange="process(this)"> </div> <div class="showchartcolor"> <label for="yellow_main"> <i style="font-size: 48px; color: #ffd778;" class="fa fa-square"></i></label> <input type="radio" id="yellow_main" name="main" value="#ffd778" onchange="process(this)"> </div> <div class="showchartcolor"> <label for="green_main"> <i style="font-size: 48px; color: #7dd483;" class="fa fa-square"></i></label> <input type="radio" id="green_main" name="main" value="#7dd483" onchange="process(this)"> </div> </div> <label> Color 2</label> <div id="showchartcolor_other"> <div class="showchartcolor"> <label for="pink_other"> <i style="font-size: 48px; color: #ff829d;" class="fa fa-square"></i></label> <input type="radio" id="pink_other" name="other" value="#ff829d"> </div> <div class="showchartcolor"> <label for="yellow_other"> <i style="font-size: 48px; color: #ffd778;" class="fa fa-square"></i></label> <input type="radio" id="yellow_other" name="other" value="#ffd778"> </div> <div class="showchartcolor"> <label for="green_other"> <i style="font-size: 48px; color: #7dd483;" class="fa fa-square"></i></label> <input type="radio" id="green_other" name="other" value="#7dd483"> </div> </div> </div> </div>
JavaScript代码
function process(rb) { const otherRadios = document.getElementsByName("other"); const targetDisabledId = rb.id.replace('main','other'); // 重置第二组所有单选框的禁用状态 for (let i = 0; i < otherRadios.length; i++) { otherRadios[i].disabled = false; } // 禁用同色对应选项 const targetRadio = document.getElementById(targetDisabledId); targetRadio.disabled = true; // 若同色选项已被选中则清除选中状态 if(targetRadio.checked) { targetRadio.checked = false; } }
修改后即可实现需求:选中Color1的任意颜色时,Color2中相同颜色的选项会自动置灰无法选中,切换Color1选项时会同步更新禁用规则。
内容的提问来源于stack exchange,提问作者Pisa Ponente
相关产品推荐
相关产品推荐

