如何计算HTML表中选中复选框的总数


How to count the total number of selected checkboxes in an HTML table

如何从这个表中计算选中的复选框的数量:

<tbody>
    <tr>
        <td>
            <center>
                <form>
                    <input type="checkbox" value="<?php echo $rws['amount']; ?>" />
                </form>
            </center>
        </td>
    </tr>
</tbody>

querySelectorAll允许您获得匹配任何CSS选择器的元素列表,因此您可以使用它来获取复选框。你可以在上面使用Array.prototype.reduce来计算被检查的数目。所以:

var count = Array.prototype.reduce.call(
    document.querySelectorAll("input[type=checkbox]"),
    function(sum, cb) {
        return sum + cb.checked ? 1 : 0;
    },
    0
);

这个回答的"类数组"部分解释了Array.prototype.reduce的使用,它让我们将querySelectorAll中的列表视为数组,而实际上它不是。

MDN有reduce如何工作的描述