简体   繁体   English

如何从复选框中获取值

[英]How to get values from checkbox

here is my code.这是我的代码。 I can't make the alert works.我无法使警报起作用。

var chooseObject = document.getElementsByTagName("input");
var objectLength = chooseObject.length;
var hobbyArray = [];
    //hobbyArray("aaa");
    //hobbyArray("bbb");
    //alert(hobbyArray); This one works.
for(var i=0;i<=objectLength;i++){
    if((chooseObject[i].type=="checkbox")&&(chooseObject[i].checked==true)){
         //alert(chooseObject[i].value); This one works.
         hobbyArray.push(chooseObject[i].value); }
}
alert(hobbyArray);

If I do the top alert(I comment already) it works.如果我执行最高警报(我已经发表评论),它会起作用。 If I alert chooseObject[i].value in the for loop, its fine.如果我在 for 循环中提醒选择对象 [i].value,那很好。 But if I do with array, it failed.但是如果我使用数组,它就失败了。 Could someone help me?有人可以帮助我吗?

You have a silly error on your for statement.你的for语句有一个愚蠢的错误。 This:这个:

for(var i=0;i<=objectLength;i++)

should be:应该:

for(var i=0;i<objectLength;i++)

The extra iteration is causing a TypeError when you check the element's properties ( chooseObject[objectLength] gives undefined , which has no properties).当您检查元素的属性时,额外的迭代会导致TypeErrorchooseObject[objectLength]给出undefined ,它没有属性)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM