You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在HTML表格的每一行添加单选框以实现行选择

解决方法

要给表格每一行添加单选框,只需在<tbody>的每一行第一列插入单选框组件,同时注意所有单选框的name属性保持一致,这样才能实现同一时间仅选中一行的效果。

修改后的完整代码

<div class="container">
      <h2> Details</h2>
      <button onclick="myFunction(1)" type="submit" class="btn btn-primary">Edit Selected Row</button>  
      <table class="table">
      <thead>
        <tr>
          <th scope="col">
            <div class="form-check">
              <input class="form-check-input" type="radio" name="rowSelector" id="selectAll">
              <label class="form-check-label" for="selectAll"></label>
            </div>
          </th>
          <th scope="col">Name</th>
          <th scope="col">Email</th>
          <th scope="col">Date</th>
          <th scope="col">Location</th>
          <th scope="col">Description</th>
          <th scope="col">Checked by</th>
          <th scope="col">Reward By</th>
        </tr>
      </thead>
      <tbody>
        <tr>
          <td>
            <div class="form-check">
              <input class="form-check-input" type="radio" name="rowSelector" id="row1">
              <label class="form-check-label" for="row1"></label>
            </div>
          </td>
          <td><a href="john@example.com">John Doe</a></td>
          <td><a href="www.john@example.com">www.john@example.com</a></td>
          <td>11/29/2022</td>
          <td>USA</td>
          <td>description here</td>
          <td><a href="Boss@example.com">Boss Man</a></td>
          <td><a href="Boss@example.com">Boss Boss Man</a></td>
        </tr>
        <!-- 更多行可按同样逻辑添加单选框 -->
        <tr>
          <td>
            <div class="form-check">
              <input class="form-check-input" type="radio" name="rowSelector" id="row2">
              <label class="form-check-label" for="row2"></label>
            </div>
          </td>
          <td><a href="jane@example.com">Jane Smith</a></td>
          <td><a href="www.jane@example.com">www.jane@example.com</a></td>
          <td>12/01/2022</td>
          <td>Canada</td>
          <td>another description</td>
          <td><a href="Boss@example.com">Boss Man</a></td>
          <td><a href="Boss@example.com">Boss Boss Man</a></td>
        </tr>
      </tbody>
      </table>
</div>

关键修改说明

  • 统一所有单选框的name为rowSelector,确保单选互斥(同一时间只能选一行)
  • 将原每行第一列的序号单元格替换为包含单选框的<td>,若需保留序号,可在单选框旁补充显示
  • 为每个单选框设置唯一id,对应label的for属性,保证组件可访问性

内容的提问来源于stack exchange,提问作者Nori

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 10:40:29