javascript - 如何引用任何给定行的表格单元格内的一组复选框

标签 javascript reference html-table

我有一个 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 来检查每个复选框的值以与其他内容进行比较。我尝试了以下方法来获取周一、周二、周三、周四和周五复选框的值,但它们似乎不起作用:

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>

关于javascript - 如何引用任何给定行的表格单元格内的一组复选框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36596382/

相关文章:

c++ - 引用在运行时确定大小的数组

mysql - 将多列 MySql 记录转换为响应式显示

html - 将表格列的宽度设置为在其下方行的内容宽度处达到最大值

javascript - Gulp - 定位文件夹及其子文件夹中的所有文件

c - 为什么在C中扫描输入时需要(&)的地址位置

javascript - Expressjs - 将表单数组/括号字段解析为实际数组

javascript - javascript如何执行带有参数的回调

垂直而不是水平的 HTML 表格?

javascript - 即使Internet Explorer浏览器在设置中禁用了音频,我们也可以通过Javascript编码播放音频吗?

javascript - 如何使用 Parse JS SDK 查询过去 7 天的对象?