如何引用表单元格中任意给定行的一组复选框

How to reference a set of checkboxes inside a table cell for any given row

本文关键字:复选框 一组 何引用 引用 表单 单元格 任意      更新时间:2024-05-26

我有一个HTML表,每行一个单元格,其中包含五个复选框:

<td class="days">
    <label><input type="checkbox" name="mon" id="mon" value="1" class="form-control" />M</label>
    <label><input type="checkbox" name="tue" id="tue" value="2" class="form-control" />Tu</label>
    <label><input type="checkbox" name="wed" id="wed" value="3" class="form-control" />W</label>
    <label><input type="checkbox" name="thu" id="thu" value="4" class="form-control" />Th</label>
    <label><input type="checkbox" name="fri" id="fri" value="5" class="form-control" />F</label>
</td>

我需要我的javaScript来检查每个复选框的值,以便与其他复选框进行比较。我尝试了以下方法来获取复选框mon、tue、wed、thu和fri的值,但它们似乎不起作用:

var table = document.getElementById("leaveTable");
var monValue = table.rows[row].cells[5].namedItem("mon").firstChild.value;

(包含复选框的单元格的索引为5)

我有多行,除了行索引之外,所有行都是相同的,这样我就可以将行索引作为参数传递给我的函数,并且无论哪一行,相同的函数都可以工作。

我只使用javaScript,而不是JQuery,所以请只回答javaScript的建议。感谢

您可以在行上使用querySelectorAll()来获取中的所有输入元素

var idx = 0;
var table = document.getElementById("leaveTable");
var inputs = table.rows[idx].querySelectorAll('input[type="checkbox"]'); //'input[type="checkbox"]:checked' if you want only checked
for (var i = 0; i < inputs.length; i++) {
  snippet.log(inputs[i].value + ':' + inputs[i].name + ':' + inputs[i].nextSibling.nodeValue)
}
<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
<table id="leaveTable">
  <tr>
    <td class="days">
      <label>
        <input type="checkbox" name="mon" id="mon" value="1" class="form-control" />M</label>
      <label>
        <input type="checkbox" name="tue" id="tue" value="2" class="form-control" />Tu</label>
      <label>
        <input type="checkbox" name="wed" id="wed" value="3" class="form-control" />W</label>
      <label>
        <input type="checkbox" name="thu" id="thu" value="4" class="form-control" />Th</label>
      <label>
        <input type="checkbox" name="fri" id="fri" value="5" class="form-control" />F</label>
    </td>
  </tr>
</table>