user1148875
user1148875

Reputation: 459

How can get length on checked checkbox array javascript

<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

Answers (11)

Hari
Hari

Reputation: 89

Try this,

var ch_n = $( "input:checked" ).length;

Upvotes: 0

Adil
Adil

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

Live Demo

$('[name="cbox[]"]:checked').length

Upvotes: 35

Nikunj K.
Nikunj K.

Reputation: 9199

You may use as below as well

$('[name=cbox\\[\\]]:checked').length

Upvotes: 0

Affan
Affan

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

user3089154
user3089154

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

Greg
Greg

Reputation: 3568

$('input:checked').length will do if you do not have any other input tags than in this form.

Upvotes: 2

Swarne27
Swarne27

Reputation: 5747

Try out,

var boxes = $('input[name="cbox[]"]:checked');

find how many are checked,

$(boxes).size();

or

$(boxes).length();

Upvotes: 0

Gaurav
Gaurav

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

user2063626
user2063626

Reputation:

Try this

jQuery solution:

var len = $(":checked",$("input[name='cbox[]']")).size();

Upvotes: 1

Sandeep
Sandeep

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

VisioN
VisioN

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

Related Questions