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

如何判断checkbox至少选择一项
NAME都不相同,有几组

比如:chk1,chk2,chk2   ;   mychk1,mychk2,mychk3

需要分别判断每组至少选择一项




------解决方案--------------------
建议你每组命名同样的name好了。然后按楼上的做法,不过改用getElementsByName

------解决方案--------------------
var chk = document.getElementsByTagName(input);
for(var i=0;i <chk.length;i++)
{
if(chk[i].type == "CHECKBOX ")
{
if(chk[i].name = "chk1 ")
{
if(chk[i].checked)
{
return true;
}
else
{
return false;
}
}
}
return false;
}
------解决方案--------------------
var chk = document.getElementsByTagName(input);
for(var i=0;i <chk.length;i++)
{
if(chk[i].type == "CHECKBOX ")
{
if(chk[i].name = "chk1 ")
{
if(chk[i].checked)
{
return true;
}
else
{
return false;
}
}
else if(chk[i].name = "chk2 ")
{
if(chk[i].checked)
{
return true;
}
else
{
return false;
}
.......................//中间的省略...
}
}
return false;
}

------解决方案--------------------
<script type= "text/javascript ">
function check(){
var av=false;
var bv=false;
box_a=document.getElementById( "a ").getElementsByTagName( "input ");
box_b=document.getElementById( "b ").getElementsByTagName( "input ");
for(var i=0;i <box_a.length;i++){
if(box_a[i].checked==true){
av=true;
break;
}
}
for(var i=0; i <box_b.length; i++){
if(box_b[i].checked==true){
bv=true;
break;
}
}
if(av!=true || bv!=true){
alert( "每个选项里至少要选择一项 ");
}
}
</script>
<div id= "a ">
<label> <input type= "checkbox " name= "checkbox " id= "a1 " value= "checkbox " /> a1 </label>
<label> <input type= "checkbox " name= "checkbox " id= "a2 " value= "checkbox " /> a2 </label>
</div>
<div id= "b ">
<label> <input type= "checkbox " name= "checkbox " id= "b1 " value= "checkbox " /> b1 </label>
<label> <input type= "checkbox " name= "checkbox " id= "b2 " value= "checkbox " /> b2 </label>
</div>
<input type= "button " onclick= "check() " value= "检查 ">
------解决方案--------------------
function check(objName) {
var obj = document.getElementsByName(objName);
var flag = false;
for (var i = 0 ; i < obj.length ; i++ ) {
if ( obj[i].checked == true) {
flag = true;
break;
}
}
return flag;
}