我有一个 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/