我想显示用户在页面上选中的复选框总数。这是我的代码。
<input type="checkbox" name="fruit" />A
<input type="checkbox" name="fruit" />B
<input type="checkbox" name="fruit" />C
<p>Total Number of Items Selected = <p>
请提供实现此目的所需的 javascript 代码。我知道之前有人问过这个问题,但我没有从这些答案中受益,因为他们要求我编辑 JS 代码以适应我的 HTML,而我目前无法做到这一点。
最佳答案
你可以使用 .querySelectorAll()
方法来选择您想要定位的所有元素,然后使用 length
方法,该方法将返回 cheched 元素的数量,例如:
document.querySelectorAll('input[name="fruit"]:checked').length;
_______________________________________________^^^^^^^ //Used to select just checked inputs
注意名称选择器input[name="fruit"]
的使用仅针对所需的输入而不是所有文档checkbox
的。
使用 jQuery 的实例:
$('input[name="fruit"]').click(function() {
console.log(document.querySelectorAll('input[name="fruit"]:checked').length);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" name="fruit" />A
<input type="checkbox" name="fruit" />B
<input type="checkbox" name="fruit" />C
关于javascript - 计算通过 JS 选中并显示在页面上的复选框总数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51562275/