Possible Duplicate:
Get number of checkboxes that are checked in Javascript
o开发者_运维知识库bj = document.getElementById('myform').elements.length.checked;
Is this the wrong code if I want to check the number of checked inputs?
You should iterate over all elements and filter the checked ones out: http://jsfiddle.net/pimvdb/Yfpt3/.
var form = document.getElemen tById('form'); // the form
var elements = form.elements; // the form's elements
var checked = []; // we will fill this with checked elements
for(var i = 0; i < elements.length; i++) { // iterate over all elements
if(elements[i].checked) { // if this one is checked
checked.push(elements[i]); // add to the checked elements array
}
}
alert(checked.length); // alert amount of checked elements
Your code will set obj to undefined as length is a number which doesn't have a property checked
. Try something like this
var el = document.getElementById('myform').elements;
var count = 0;
for (var i = 0; i < el.length; i++)
{
if(el[i].type == "checkbox" && el[i].checked)
{
count++
}
}
alert(count);
精彩评论