<form name='form1' >
<input type=checkbox name='cbox[]' />
</form>
<script>
var checkbox = document.getElementsByName('ckbox[]')
var ln = checkbox.length
alert(ln)
</script>
How can I count only the checked checkboxes with JavaScript or jQuery?
So user can select as many checkboxes they want but sum can't exceed 10.
Doing it with jQuery would shorten the code and make it more readable, maintainable and easier to understand. Use attribute selector with :checked selector
Live Demo
$('[name="cbox[]"]:checked').length
If you want to use plain javascript
var checkbox = document.getElementsByName('ckbox[]');
var ln = 0;
for(var i=0; i< checkbox.length; i++) {
if(checkbox[i].checked)
ln++
}
alert(ln)
jQuery solution:
var len = $("[name='cbox[]']:checked").length;
JavaScript solution:
var len = [].slice.call(document.querySelectorAll("[name='cbox[]']"))
.filter(function(e) { return e.checked; }).length;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With