Wednesday, August 21, 2013

Read Multiple checkbox value and Radio button value at client side and serverside using jsp

Html file


 <html>  
 <head>  
 <title>Check Box Example</title>  
 <script src="jquery.js"></script>  
 <script>  
 function checkdisp()  
 {  
       $('input[name="hobby"]:checked').each(function()  
       {  
      alert("Check Button Value:"+$(this).val());  
    });  
      alert("The Radio Button Value:"+$('input[name="gen"]:checked').val());  
 }  
 </script>  
 </head>  
 <body>  
 <form name="frmpdf" action="connectCheck.jsp" method="GET">  
 Hobbies:<br>  
            <input type="checkbox" name="hobby" value="Cricket">Cricket<br>  
            <input type="checkbox" name="hobby" value="Movie">Watching Movie<br>  
            <input type="checkbox" name="hobby" value="Book">Reading Book<br>  
            <br>  
 Gender:<input type="radio" value="Male" name="gen" Checked>Male  
           <input type="radio" value="Female" name="gen">Female  
           <br>  
            <input type="button" value="ClientSide" onclick="checkdisp()">  
            <input type="submit" value="ServerSide">  
 </form>  
 </body>  
 </html>  


jsp file
connectCheck.jsp
 <%  
      out.println("CheckBox Value");  
      String[] checkb=request.getParameterValues("hobby");  
      try  
      {  
           for(int i=0;i<checkb.length;i++)  
                out.println(checkb[i]);  
           out.println("Radio Button value");  
           String radiob=request.getParameter("gen");  
           out.println(radiob);  
      }  
      catch(Exception e)  
      {  
           out.println("erro "+e.toString());  
      }  
 %>  

Client side : when you click on clientSide button it will display value of selected Checkbox and Radio button in Html File using jquery.

Server side:after selecting value in html page when you click on servierSide button it  will got to connectCheck.jsp page that print the selected checkbox and Radio button value.
           i used try and catch block because if user is not selected checkbox value and you try to access then its will throw error so handling exceptin i used try and catch block.