java 複選框的取值與驗證(checkbox)
阿新 • • 發佈:2019-01-24
表單如下:
<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);
}
}
<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);
}
}