简体   繁体   中英

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.

Right now I have the following JavaScript code:

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.

If you're able to modify the HTML of your checkboxes, I would group them using a class.

<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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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