如何用JavaScript实现单选按钮限制:M、L列各仅选一个
问题描述
给定如下HTML表格代码:
<div class="container"> <table class="table table-striped"> <thead> <tr> <th scope="col">#</th> <th scope="col">question</th> <th scope="col">M</th> <th scope="col">L</th> </tr> </thead> <tbody> <tr> <th scope="row">1</th> <td>Mark</td> <td><input type="radio" id="1q1m" name="fav_language" value="M"></td> <td><input type="radio" id="1q1l" name="fav_language" value="L"></td> </tr> <tr> <th scope="row">2</th> <td>Mark</td> <td><input type="radio" id="1q2m" name="fav_language2" value="M"></td> <td><input type="radio" id="1q2l" name="fav_language2" value="L"></td> </tr> <tr> <th scope="row">3</th> <td>Mark</td> <td><input type="radio" id="1q3m" name="fav_language3" value="M"></td> <td><input type="radio" id="1q3l" name="fav_language3" value="L"></td> </tr> <tr> <th scope="row">4</th> <td>Mark</td> <td><input type="radio" id="1q4m" name="fav_language4" value="M"></td> <td><input type="radio" id="1q4l" name="fav_language4" value="L"></td> </tr> </tbody> </table> </div>
需求:使用JavaScript实现每列仅能选中一个选项——也就是所有值为M的单选按钮只能选中一个,所有值为L的单选按钮也只能选中一个,阻止用户多选。
解决方案
思路说明
原来的HTML里,单选按钮是按行设置name属性的,所以同一行的M和L互斥,但不同行的M可以同时选中。要实现列内互斥,有两种可行方式:
方案1:修改HTML(最简单)
直接调整单选按钮的name属性,让同一列的单选共用同一个name:
- 所有M列的单选
name设为column_m - 所有L列的单选
name设为column_l
修改后的核心HTML片段:
<tr> <th scope="row">1</th> <td>Mark</td> <td><input type="radio" id="1q1m" name="column_m" value="M"></td> <td><input type="radio" id="1q1l" name="column_l" value="L"></td> </tr> <tr> <th scope="row">2</th> <td>Mark</td> <td><input type="radio" id="1q2m" name="column_m" value="M"></td> <td><input type="radio" id="1q2l" name="column_l" value="L"></td> </tr> <!-- 剩下两行同理修改name属性 -->
这种方式不需要额外写JavaScript,利用单选按钮原生的互斥特性就能实现需求。
方案2:纯JavaScript控制(不修改HTML)
如果无法改动现有HTML,就通过监听单选按钮的change事件,当某列的单选被选中时,取消同列其他单选的选中状态:
// 获取所有M值的单选按钮 const mRadios = document.querySelectorAll('input[type="radio"][value="M"]'); // 获取所有L值的单选按钮 const lRadios = document.querySelectorAll('input[type="radio"][value="L"]'); // 给M列的单选绑定事件 mRadios.forEach(radio => { radio.addEventListener('change', () => { if (radio.checked) { // 取消其他M单选的选中状态 mRadios.forEach(r => { if (r !== radio) r.checked = false; }); } }); }); // 给L列的单选绑定事件 lRadios.forEach(radio => { radio.addEventListener('change', () => { if (radio.checked) { // 取消其他L单选的选中状态 lRadios.forEach(r => { if (r !== radio) r.checked = false; }); } }); });
把这段代码放在HTML底部(或者用DOMContentLoaded事件包裹),就能实现列内单选互斥的效果。
补充:获取选中值
如果需要获取用户选中的M、L列值,可以用以下代码:
// 获取选中的M列单选值 const selectedM = document.querySelector('input[type="radio"][value="M"]:checked')?.value; // 获取选中的L列单选值 const selectedL = document.querySelector('input[type="radio"][value="L"]:checked')?.value;
内容的提问来源于stack exchange,提问作者mutaib al otaibi
相关产品推荐
相关产品推荐

