表单如下:
<form name="form1" action="test.jsp" method="post" onsubmit="return checkData();">
<input name="checkall1" type="checkbox" value="0" onClick="checkAllBox(this);"/>全选<br>
<input name="answer" type="checkbox" value="a"/>A<br>
<input name="answer" type="checkbox" value="b"/>B<br>
<input name="answer" type="checkbox" value="c"/>C<br>
<input name="answer" type="checkbox" value="d"/>D<br>
<input name="answer" type="checkbox" value="e"/>E<br>
<input name="answer" type="checkbox" value="f"/>F<br>
</form>
全选及验证javascript如下:
<script type="text/javascript">
function checkAllBox(obj){
var answer= document.getElementsByName("answer");
if(obj.checked==true){
for(var i=0;i<answer.length;i++){
answer[i].checked = true;
}
}else{
for(var i=0;i<answer.length;i++){
answer[i].checked = false;
}
}
}
function checkData(){
var answer= document.getElementsByName("answer");
var flag = false;
for(var i=0;i<income.length;i++){
if(income[i].checked == true){
flag = true;
break;
}
}
if(!flag){
alert("请至少选择一项");
}
return flag;
}
</script>
test.jsp中取值如下:
String[] answer= request.getParameterValues("answer");//这里只取得了选中的项,如果没有选中任何一项,则为null
if(answer!=null){
for(String i:answer){
System.out.println(i);
}
}