Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 902
user1148875 Avatar asked Feb 27 '13 11:02

user1148875


People also ask

How many checkboxes we can check at a time?

So user can select as many checkboxes they want but sum can't exceed 10.


3 Answers

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
like image 159
Adil Avatar answered Oct 06 '22 18:10

Adil


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)
like image 43
Sandeep Avatar answered Oct 06 '22 17:10

Sandeep


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;
like image 44
VisioN Avatar answered Oct 06 '22 17:10

VisioN