计算HTML中选中的复选框的数量

计算HTML中选中的复选框的数量

本文介绍了计算HTML中选中的复选框的数量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,基本上我想统计所打勾的复选框的数量.我将代码设置为可以成功计数的点,但是我想添加一个警报,其中显示选中的复选框数量,代码可以执行此操作,但不显示总计数,它会在每次刷新时增加总计数.我只想知道如何显示总数.

So basically i want to count the number of checkboxes that are ticked. I get my code to the point where it counts them successfully, but I want to put in an alert that shows the number of checkboxes ticked, the code does this but doesn't show the total count, it increments the total every refresh. I just want to know how I can show a total count.

单击单选按钮是"时,它应该显示总计.

It should display the total when the radio button 'yes' is clicked.

<br />Apples
<input type="checkbox" name="fruit" />Oranges
<input type="checkbox" name="fruit" />Mango
<input type="checkbox" name="fruit" />
<br />Yes
<input type="radio" name="yesorno" id="yes" onchange="checkboxes()"
function checkboxes(){
    var inputElems = document.getElementsByTagName("input"),
    count = 0;
    for (var i=0; i<inputElems.length; i++) {
    if (inputElems[i].type === "checkbox" && inputElems[i].checked === true){
        count++;
        alert(count);
    }
}}

推荐答案

这应该可以解决问题:

alert(document.querySelectorAll('input[type="checkbox"]:checked').length);

这篇关于计算HTML中选中的复选框的数量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-30 18:23