Reputation: 459
<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?
Upvotes: 16
Views: 92278
Reputation: 148110
Doing it with jQuery would shorten the code and make it more readable, maintainable and easier to understand. Use attribute selector with :checked selector
$('[name="cbox[]"]:checked').length
Upvotes: 35
Reputation: 9199
You may use as below as well
$('[name=cbox\\[\\]]:checked').length
Upvotes: 0
Reputation: 31
you also do by this
you have to define class for checkBox and then follow below
var chkLength = $('input.className:checked').length; alert(chkLength);
this will print your total no of checkboxes from list
Upvotes: 0
Reputation: 1
var len = $("[name='cbox[]']:checked").length;
will work but will not work if you are directly comparing like
if ( $("[name='cbox[]']").length= $("[name='cbox[]']:checked").length)
Upvotes: 0
Reputation: 3568
$('input:checked').length
will do if you do not have any other input tags than in this form.
Upvotes: 2
Reputation: 5747
Try out,
var boxes = $('input[name="cbox[]"]:checked');
find how many are checked,
$(boxes).size();
or
$(boxes).length();
Upvotes: 0
Reputation: 1098
var fobj = document.forms[0];
var c = 0;
for (var i = 0; i < formobj.elements.length; i++)
{
if (fobj.elements[i].type == "checkbox")
{
if (fobj.elements[i].checked)
{
c++;
}
}
}
alert('Total Checked = ' + c);
Upvotes: 1
Reputation:
Try this
jQuery solution:
var len = $(":checked",$("input[name='cbox[]']")).size();
Upvotes: 1
Reputation: 2121
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)
Upvotes: 7
Reputation: 145398
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;
Upvotes: 4