Javascript 如何计算每个选中的复选框
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14725969/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to count every checked checkboxes
提问by hawkidoki
Here is my code :
这是我的代码:
It actually count checked checkboxes and write it inside <span class="counter"></span>. This code works on Firefox, but not on Chrome.
它实际上计算选中的复选框并将其写在里面<span class="counter"></span>。此代码适用于 Firefox,但不适用于 Chrome。
On Chrome, the .select_all check all checkboxes I want, but doesn't update the counter. Actually counter get updated when I uncheck the .select_all, which is weird.
在 Chrome 上, .select_all 选中我想要的所有复选框,但不会更新计数器。当我取消选中 .select_all 时,计数器实际上会更新,这很奇怪。
IMPORTANT FACT: I don't want to count the .Select_all checkboxes inside my .counter
重要事实:我不想计算 .counter 中的 .Select_all 复选框
jQuery(document).ready(function($){
$(function() {
$('#general i .counter').text(' ');
var generallen = $("#general-content input[name='wpmm[]']:checked").length;
if(generallen>0){$("#general i .counter").text('('+generallen+')');}else{$("#general i .counter").text(' ');}
})
$("#general-content input:checkbox").on("change", function() {
var len = $("#general-content input[name='wpmm[]']:checked").length;
if(len>0){$("#general i .counter").text('('+len+')');}else{$("#general i .counter").text(' ');}
});
$(function() {
$('.select_all').change(function() {
var checkthis = $(this);
var checkboxes = $(this).parent().next('ul').find("input[name='wpmm[]']");
if(checkthis.is(':checked')) {
checkboxes.attr('checked', true);
} else {
checkboxes.attr('checked', false);
}
});
});
});
EDIT: Here is a example document of the code : http://jsfiddle.net/8PVDy/1/
编辑:这是代码的示例文档:http: //jsfiddle.net/8PVDy/1/
回答by gabitzish
You can use a function to update the counter :
您可以使用函数来更新计数器:
function updateCounter() {
var len = $("#general-content input[name='wpmm[]']:checked").length;
if(len>0){$("#general i .counter").text('('+len+')');}else{$("#general i .counter").text(' ');}
}
and call this function when a checkbox's state is changed (including the selectAll checkboxes)
并在复选框的状态更改时调用此函数(包括 selectAll 复选框)
Here is an updated jsFiddle : http://jsfiddle.net/8PVDy/4/
这是更新的 jsFiddle:http: //jsfiddle.net/8PVDy/4/
回答by nbrooks
$('input[type="checkbox"]:checked').length
回答by Roger
you can do it this way
你可以这样做
$(document).ready(function(){
$('input[type="checkbox"]').click(function(){
alert($('.test:checked').length);
});
});
HTML i used
我使用的 HTML
<input type="checkbox" name="test" class="test" value=""/>
<input type="checkbox" name="test" class="test" value=""/>
<input type="checkbox" name="test" class="test" value=""/>
<input type="checkbox" name="checkAll" class="checkAll" value=""/>
Hope this helps
希望这可以帮助
回答by Arun P Johny
For updating the checked status use the jQuery.prop()function
要更新选中状态,请使用jQuery.prop()函数
Code:
代码:
$(function(){
$('#general i .counter').text(' ');
var fnUpdateCount = function() {
var generallen = $("#general-content input[name='wpmm[]']:checked").length;
console.log(generallen,$("#general i .counter") )
if (generallen > 0) {
$("#general i .counter").text('(' + generallen + ')');
} else {
$("#general i .counter").text(' ');
}
};
$("#general-content input:checkbox").on("change", function() {
fnUpdateCount();
});
$('.select_all').change(function() {
var checkthis = $(this);
var checkboxes = $("#general-content input:checkbox");
if (checkthis.is(':checked')) {
checkboxes.prop('checked', true);
} else {
checkboxes.prop('checked', false);
}
fnUpdateCount();
});
});
Demo: Fiddle
演示:小提琴
回答by mkbctrl
What I found missing in all above answers is an explanation about how to listen to clicks in an efficient way since the question is tightly coupled with onChange event. Another thing is that question doesn't specify whether the code should be only in Jquery I think that adding vanilla JS solution should be a good idea.
我在上述所有答案中发现缺少的是关于如何以有效的方式收听点击的解释,因为该问题与 onChange 事件紧密相关。另一件事是这个问题没有指定代码是否应该只在 Jquery 中我认为添加 vanilla JS 解决方案应该是一个好主意。
Here's the HTML list of checkboxes the I will be counting. I have approched the question in a little bit more generic way, to make it easier to apply in different conditions. I plan to count checkboxes globally and per each section.
这是我将计算的复选框的 HTML 列表。我以更通用的方式解决了这个问题,以便更容易在不同条件下应用。我计划在全局和每个部分计算复选框。
<div class="wrapper">
<section class="list list-1">
<label for="id-11"><input type="checkbox" id="id-11"></label>
<label for="id-12"><input type="checkbox" id="id-12"></label>
<label for="id-13"><input type="checkbox" id="id-13"></label>
<label for="id-14"><input type="checkbox" id="id-14"></label>
<label for="id-15"><input type="checkbox" id="id-15"></label>
<label for="id-16"><input type="checkbox" id="id-16"></label>
<label for="id-17"><input type="checkbox" id="id-17"></label>
<label for="id-18"><input type="checkbox" id="id-18"></label>
<label for="id-19"><input type="checkbox" id="id-19"></label>
<label for="id-110"><input type="checkbox" id="id-110"></label>
<span class="list-score">Section 1: <span class="number">0</span></span>
</section>
<section class="list list-2">
<label for="id-21"><input type="checkbox" id="id-21"></label>
<label for="id-22"><input type="checkbox" id="id-22"></label>
<label for="id-23"><input type="checkbox" id="id-23"></label>
<label for="id-24"><input type="checkbox" id="id-24"></label>
<label for="id-25"><input type="checkbox" id="id-25"></label>
<label for="id-26"><input type="checkbox" id="id-26"></label>
<label for="id-27"><input type="checkbox" id="id-27"></label>
<label for="id-28"><input type="checkbox" id="id-28"></label>
<label for="id-29"><input type="checkbox" id="id-29"></label>
<label for="id-210"><input type="checkbox" id="id-210"></label>
<span class="list-score">Section 2: <span class="number">0</span></span>
</section>
<section class="list list-3">
<label for="id-31"><input type="checkbox" id="id-31"></label>
<label for="id-32"><input type="checkbox" id="id-32"></label>
<label for="id-33"><input type="checkbox" id="id-33"></label>
<label for="id-34"><input type="checkbox" id="id-34"></label>
<label for="id-35"><input type="checkbox" id="id-35"></label>
<label for="id-36"><input type="checkbox" id="id-36"></label>
<label for="id-37"><input type="checkbox" id="id-37"></label>
<label for="id-38"><input type="checkbox" id="id-38"></label>
<label for="id-39"><input type="checkbox" id="id-39"></label>
<label for="id-310"><input type="checkbox" id="id-310"></label>
<span class="list-score">Section 3: <span class="number">0</span></span>
</section>
<span class="total-score">Total: <span class="number">0</span></span>
</div>
and here's the JS markup, that listens to all clicks inside the .wrapperdiv and counts selected inputs in the context of the .wrapperand each .listsection.
这是 JS 标记,它侦听.wrapperdiv内的所有点击,并在.wrapper和每个.list部分的上下文中计算选定的输入。
const total = document.querySelector('.total-score .number')
document.querySelector('.wrapper').addEventListener('change', function(event) { // First we apply the ONLY one listener to do the listening for us - we don't need listener on each checkbox
const numberAll = this.querySelectorAll('input[type="checkbox"]:checked').length // We count all selected inputs in side the main wrapper.
total.innerHTML = numberAll // We update the total counter
const list = event.target.closest('.list') // We look and cache the closest section, wrapping the clicked checkbox element
const numberList = list.querySelectorAll('input[type="checkbox"]:checked').length // Once found, we start to count the number of selected checboxes under the section
list.querySelector('.list-score .number').innerHTML = numberList // We update the sectiona relevant counter
})
Here's the live example in the JS fiddle: https://jsfiddle.net/mkbctrlll/yak4oqj9/159/
这是 JS 小提琴中的现场示例:https: //jsfiddle.net/mkbctrlll/yak4oqj9/159/
In Vanilla JS you have to be aware that applying the changelistener to each checkbox is much slower solution. Instead you should make use of so called event delegation and apply the listener to the wrapping element or even to whole document.
在 Vanilla JS 中,您必须意识到将change侦听器应用于每个复选框是慢得多的解决方案。相反,您应该使用所谓的事件委托并将侦听器应用于包装元素甚至整个文档。
Here you can check it by yourself, how much slower is listening to change per each input in your list:
在这里,您可以自己检查一下,列表中每个输入的更改速度有多慢:
https://jsperf.com/change-listener-on-each-vs-event-delegation/1
https://jsperf.com/change-listener-on-each-vs-event-delegation/1
The code for the slower option (just to compare):
较慢选项的代码(只是为了比较):
document.querySelector('.wrapper').addEventListener('change', function() {
const numberAll = this.querySelectorAll('input[type="checkbox"]:checked').length
total.innerHTML = numberAll
})
document.querySelectorAll('.list').forEach((list) => {
list.addEventListener('change', function() {
const numberAll = this.querySelectorAll('input[type="checkbox"]:checked').length
this.querySelector('.list-score .number').innerHTML = numberAll
})
})
and my solution in jQuery:
和我在 jQuery 中的解决方案:
$('.wrapper').change(function() {
const numberAll = $(this).find('input[type="checkbox"]:checked').length
total.innerHTML = numberAll
const $list = $(event.target).closest('.list')
const numberList = $list.find('input[type="checkbox"]:checked').length
$($list.find('.list-score .number')).html(numberList)
})
P.S. I tried adding jQuery solution to the benchmark too, but it's performance seemed to be fake, so I decided to go without it.
PS 我也尝试将 jQuery 解决方案添加到基准测试中,但它的性能似乎是假的,所以我决定不使用它。
回答by KBN
Try this.
尝试这个。
$('.select_all').change(function() {
var num = $(this).find("input[name='wpmm[]']:checked").length;
$("#general .counter").html(num);
});
回答by Ledhund
Modified the select all-handler to trigger the onchange function for the sub-category checkboxes like this
修改select all-handler触发子类checkbox的onchange函数是这样的
$(function() {
$('.select_all').change(function() {
var checkthis = $(this);
var checkboxes = $(this).parent().next('ul').find("input[name='wpmm[]']");
if(checkthis.is(':checked')) {
checkboxes.attr('checked', true);
} else {
checkboxes.attr('checked', false);
}
// make sure to trigger the onchange behaviour for the checkboxes
$("#general-content input:checkbox").change();
});
})
I seem to remember that there is a prettier way to trigger them, but can't find it
好像记得有比较漂亮的触发方式,但是找不到

