1. 程式人生 > >JS和後臺獲取複選框(checkbox)選中項後的文字內容

JS和後臺獲取複選框(checkbox)選中項後的文字內容

<!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 runat="server">
    <title>無標題頁</title>
    
 <script language=javascript>


//單選與全選的判斷
function check(e, allName){
       var all = document.getElementsByName(allName)[0];    //獲取全選複選框
       if(!e.checked){
           //沒被選中全選複選框置為false;
           all.checked = false;
       } else {
           //選中,遍歷陣列
           var aa = document.getElementsByName(e.name);
           for (var i=0; i<aa.length; i++)
           //只要陣列中有一個沒有選中返回。假如所有的都是選中狀態就將全選複選框選中;
           if(!aa[i].checked) return;    
           all.checked = true;  
       }
   }


//複選框的選擇
function checkSub(e, itemName){
  var aa = document.getElementsByName(itemName);
  for (var i=0; i<aa.length; i++){
   aa[i].checked = e.checked;
}
}


//傳送前檢查
function checkItem(itemName){
     var aa = document.getElementsByName(itemName);
     var flag = true;
     for (var i=0; i<aa.length; i++){
         if(aa[i].checked){
             alert(r[i].value+","+r[i].nextSibling.nodeValue);
             flag = false;
         }
         
     }
     if(flag){
         alert("至少選一個");
         return true;
     }else{
         sendDBs();
     } 
}


var tisub = "first";
function sendDBs(){
   if("first"==tisub){
      tisub = "other";
  document.all.myform.action="<%=path %>/SendDBction.do?method=sendDB";
  document.all.myform.submit();
}
}




</script>






</head>
<body>
 <form id="myform" name="myform" method="post" id="myform" action="" >


<input name="id"  type="checkbox" onclick="check(this, 'checkAll')" value="1"/> 開


<input name="id"  type="checkbox" onclick="check(this, 'checkAll')" value="2"/> 開


<input name="id"  type="checkbox" onclick="check(this, 'checkAll')" value="3"/> 心


<input name="id"  type="checkbox" onclick="check(this, 'checkAll')" value="4"/> 心


<input name="chkAll" type="checkbox" id="chkAll" onclick="CheckAll(this,'id')" value=""/>
全選




<input type="button" onclick="aa('id')" value="選中值"/>




  
</form>




</body>
</html>
</body>
</html>





後臺獲取checkbox的值,只需一句程式碼:
String[] st = request.getParameterValues("id");即可得到String型別的陣列。




若是表單的value值是動態的,並且後臺希望獲得兩個動態值的話,
也即表單<input>如下:<input name="id"  type="checkbox" onclick="check(this, 'checkAll')"  value="<%=uid%>">
String[] st = request.getParameterValues("id")在後臺只能獲取uid的陣列,現在還想獲取uname值,怎麼辦呢?這是可以再加一個<input />,比如
<input name="id"  type="checkbox" onclick="check(this, 'checkAll')" value="<%=uid%>"/> 心
<input name="name"  type="hidden" onclick="check(this, 'checkAll')" value="<%=uname%>"/> (隱藏input)
提交表單時<input type="button" onclick="aa('id','name')" value="選中值"/>
在後臺
String[] st1 = request.getParameterValues("id");
String[] st2 = request.getParameterValues("name");