eg:
<form action="" method="post" name="form1">
<input type="text" name="txt[]"><br/>
<input type="text" name="txt[]"><br/>
选项1:<input type="checkbox" name="chk[]" value="one"><br/>
选项2:<input type="checkbox" name="chk[]" value="two"><br/>
<input type="text" id="hint" size="50">
<input type="submit" value="check it" name="Submit"> <input type="button" value="点击" onclick="myfunction()">
</form>
在上面这段代码中,当点击submit控件时,可以在脚本页通过php取得text,checkbox的数组形式。
<?php
var_dump($_POST['chk']);
此时$_POST['chk']是有被选中的checkbox组成的数组。如果checkbox都没有选中,则isset($_POST['chk'])为false;
?>
但是在上面代码中加上js代码
<script>
function myfunction()
{
var chk=document.getElementsByName("chk");
alert(chk.length);
var txt="你的选择为:";
for(var i=0;i<chk.length;i++)
{
if(chk[i].checked)
{
txt+=chk[i].value+" ";
}
}
document.getElementById("hint").value=txt;
}
</script>
此时alert(chk.length);显示为0.
这是因为document.getElementsByName("chk")的缘故
如果要document.getElementsByName("chk")有效果,需要将<input type="chkbox" name="chk[]">改为<input type="chkbox" jname="chk">
在<input type="chkbox" name="chk[]">的情况下只有document.getElementsByName("chk[]")
时,alert(chk.length)才会显示数量