开发者

Checked inputs length [duplicate]

开发者 https://www.devze.com 2023-04-05 10:52 出处:网络
This question already has answers here: Closed 11 years ago. Possible Duplicate: Get number of checkboxes that are checked in Javascript
This question already has answers here: Closed 11 years ago.

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);
0

精彩评论

暂无评论...
验证码 换一张
取 消