简体   繁体   English

Javascript计数已选中复选框,而不计数另一个复选框

[英]Javascript count checked checkbox and not count another checkbox

I'm trying to have JavaScript count one set of checkboxes and not count a set of checkboxes. 我正在尝试让JavaScript计数一组复选框,而不计数一组复选框。

Right now I have the following JavaScript code: 现在,我有以下JavaScript代码:

function updateCount {
    var count = $("input[type=checkbox]:checked").size();
    $("#count").text(count);    
};
});

Here are my checkboxes: 这是我的复选框:

<input type="checkbox" name="checkbox_1">Checkbox 1
<input type="checkbox" name="checkbox_2">Checkbox 2

So basically with my JavaScript is there a way to only count the first checkbox but not the second checkbox. 因此,基本上我的JavaScript可以只计算第一个复选框,而不计算第二个复选框。

If you're able to modify the HTML of your checkboxes, I would group them using a class. 如果您能够修改复选框的HTML,我将使用一个类对它们进行分组。

<input class="countThis" type="checkbox" name="checkbox_1">Checkbox 1
<input class="countThis" type="checkbox" name="checkbox_2">Checkbox 2

And just leave that class off anything you don't want to count 并让该班别让您不想数的东西

<input type="checkbox" name="checkbox_3">Checkbox 3
<input type="checkbox" name="checkbox_4">Checkbox 4

And finally, your function would just look like this 最后,您的函数将如下所示

function updateCount {
    var count = $(".countThis:checked").size();
    $("#count").text(count);    
};

There are two easy ways to do this. 有两种简单的方法可以做到这一点。

First, if you want to pick which checkbox to count: 首先,如果要选择要计数的复选框:

$('input[type=checkbox][name="checkbox_1"]').length

Second, if you want to pick which checkbox to exclude: 其次,如果要选择要排除的复选框:

$('input[type=checkbox][name!="checkbox_2"]').length

If you always need just the first element you can do it using :first-of-type selector: 如果您始终只需要第一个元素,则可以使用:first-of-type选择器:

$( "input[type='checkbox']:first-of-type" ).prop({
checked: true
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM