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

checkbox多笔id判定问题
有尝试写但没有成功
请问如何检查checkbox的id="main1[]"是有勾选的?

<script>
function check() {
var f = document.getElementById('main1[]');
for (var i=0;i<f.elements.length;i++) {
var e = f.elements[i];
if (e.type == \"checkbox\" && e.checked)
return true;
}
alert(\"至少选一项\");
return false;
}
</script>
<form id=\"form\" name=\"form\" method=\"post\" onsubmit=\"return check();\">
<input type=\"checkbox\" name=\"add[]\" id=\"main1[]\" value=\"1\"/>
.
.
.
<input type=\"checkbox\" name=\"add[]\" id=\"main1[]\" value=\"6\"/>

<input type=\"checkbox\" name=\"add[]\" id=\"add\" value=\"7\"/>
.
.
.
<input type=\"checkbox\" name=\"add[]\" id=\"add\" value=\"10\"/>
</form>

------解决方案--------------------
在input元素上加一个有规律的id,循环遍历这些id来判断


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
 
</head>
<body>
<input type="checkbox" id="chk0" name="chk" value="1" />1<br />
<input type="checkbox" id="chk1" name="chk" value="2" />2<br />
<input type="checkbox" id="chk2" name="chk" value="3" />3<br />
<input type="checkbox" id="chk3" name="chk" value="4" />4<br />
<input type="checkbox" id="chk4" name="chk" value="5" />5<br />
<input type="button" id="btn" value="click" onclick="btnClick();" />
<script type="text/javascript">
    function btnClick()
    {
for(var i=0;i<5;i++)
{
var chk=document.getElementById("chk"+i);

if(chk.checked)
{
alert(chk.value + "is checked");
}
}
    }
</script>
 
 
</body>
</html>

------解决方案--------------------
	<input type="checkbox" id="main1[]" name="chk" value="1" />1
<br />
<input type="checkbox" id="main1[]" name="chk" value="2" />2
<br />
<input type="checkbox" id="main1[]" name="chk" value="3" />3
<br />
<input type="checkbox" id="chk3" name="chk" value="4" />4
<br />
<input type="checkbox" id="chk4" name="chk" value="5" />5
<br />
<input type="button" id="btn" value="click" onclick="btnClick();" />
<script type="text/javascript">
var $input = document.getElementsByTagName('input');
var $main1s = (function($input) {
var i = 0, result = [];
for (; i < $input.length; i++) {