检查输入长度

时间:2011-09-18 09:00:07

标签: javascript input checkbox

  

可能重复:
  Get number of checkboxes that are checked in Javascript

obj = document.getElementById('myform').elements.length.checked;    

如果我想检查已检查输入的数量,这是错误的代码吗?

2 个答案:

答案 0 :(得分:3)

您应该遍历所有元素并过滤掉已检查的元素: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

答案 1 :(得分:2)

您的代码会将obj设置为undefined,因为length是一个没有属性checked的数字。试试这样的事情

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