【问题标题】:Count total number of checkboxes what are checked and show on page via JS计算通过 JS 检查并显示在页面上的复选框总数
【发布时间】:2019-01-04 20:00:10
【问题描述】:

我想显示用户在页面上选择的复选框总数。这是我的代码。

<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,而我目前无法做到这一点。

【问题讨论】:

标签: javascript html checkbox


【解决方案1】:

您可以使用 .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

【讨论】:

  • 问题没有提到jQuery。
  • $('input[name="fruit"]')&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"&gt;&lt;/script&gt;?
  • 这不是建议的解决方案的一部分,只是为了展示一个活生生的例子......你知道
【解决方案2】:

您可以使用查询选择器。

document.querySelectorAll("input:checked").length;

请注意,这将选中文档中的所有复选框。如果你只是想引用某一组复选框,则为组中的所有复选框赋予相同的名称,并像这样引用它们:

document.querySelectorAll("input[name='name']:checked").length;//replace 'name' with the name of the checkboxes

<input type="checkbox" name="fruit" />A
<input type="checkbox" name="fruit" />B
<input type="checkbox" name="fruit" />C

<p id="result">Total Number of Items Selected = <p>  
<script>
showChecked();
function showChecked(){
  document.getElementById("result").textContent = "Total Number of Items Selected = " + document.querySelectorAll("input:checked").length;
}
document.querySelectorAll("input[name=fruit]").forEach(i=>{
 i.onclick = function(){
  showChecked();
 }
});
</script>

【讨论】:

  • 您建议的解决方案将选择当前文档中的所有checkbox
  • @ZakariaAcharki 你说得对,我已经编辑了我的答案。
  • 现在你有了我建议的解决方案的副本:D
  • @Sali 没问题。
【解决方案3】:

虽然您请求了 JavaScript 解决方案,但这可以单独使用 CSS 来实现:

/* specifies the named counter that will be incremented by
   each checked check-box: */
input[type=checkbox]:checked {
  counter-increment: checked;
}

/* shows the counter in the '::after' pseudo-element of the
   sibling <p> element: */
p::after {
  content: ' ' counter(checked);
}
<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>

【讨论】:

  • 非常感谢!这也有效!不知道可以通过CSS实现,是不是兼容所有新旧浏览器?
  • 你必须检查兼容性以确保——例如caniuse——但我认为大多数浏览器都支持它,从 IE 10 开始。
  • 感谢 Dave 的输入和扩展我的知识,我已将其保存以备将来使用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-30
  • 2019-03-23
  • 1970-01-01
  • 2017-03-20
相关资源
最近更新 更多