日期:2014-05-16  浏览次数:20300 次

JS测试多选框的个数为什么会这样?
<form   method= "post "   onSubmit= "return   chkBox(); ">
<input   type= "submit "   id= "btnSubmit "   value= "   提   交   "   />
<input   type= "checkbox "   name= "test[] "   id= "test "   /> 测试一  
<input   type= "checkbox "   name= "test[] "   id= "test "   /> 测试二
</form>
<script   language= "javascript ">
function   chkBox   ()
{
var   arr   =   document.all( "test ");
                  //var   arr   =   document.getElementById( "test ");
alert(arr.length);
return   false;
}
</script>
这个能正常显示出 "arr.length "多选框有2个。

但是当把   ' <input   type= "checkbox "   name= "test[] "   id= "test "   /> 测试二 '   这个多选框去掉,只留下“测试一”这个多选框。那弹出来的arr.length本应是1的。但是却弹出“未定义(undefine)”,为啥啊?对多选框的length只有一个时,测试不出来吗?有啥好的解决方法没?

------解决方案--------------------
alert(document.getElementsByName( "test[] ").length);
------解决方案--------------------
<form method= "post " onSubmit= "return chkBox(); ">
<input type= "submit " id= "btnSubmit " value= " 提 交 " />
<input type= "checkbox " name= "test " /> 测试一
<input type= "checkbox " name= "test " /> 测试二
</form>
<script language= "javascript ">
function chkBox ()
{
var arr=document.getElementsByName( "test ");
alert(arr.length);
return false;
}
</script>