We help IT Professionals succeed at work.

save multiple checkbox values

cofactor
cofactor asked
on
922 Views
Last Modified: 2012-05-09
I want to keep  multiple checkboxes in the JSP page . I want to save and retrieve their values .
Could you please help me to find a  easy and best  solution ? I'm explaining below where I need help.



Question :

Q1: What should be the checkbox names ?

Example:  

I have existing code ..
..................
..................
while (regioniterator.hasNext()){
  String region = (String)regioniterator.next(); // get the key

 // I want to create 15 checkboxes  for each region . How do I keep the checkbox name ?
 // Here is a proposed design . is this a good design  ?

   for(int j=0;j<15;j++){ % > <input type="checkbox"    name="<%=region><%=j>" value="" align="middle"> <% }%>

 }



 Q2:

 When the form  be submitted to the action class. How do I retrieve them in the action class ?
 I'm stuck here . Because all those many checkboxes are created dynamically .  I can not use request.getParameterName() now in the action class to retrieve from the request .

 What trick to apply here ?


 Q3:

 How do I save so many checkbox values in the DB ? I need to save and retrieve their values  in the JSP also.

 What table and how many column to make here to hold their values  ?
 
 How the table design will look like ?
Comment
Watch Question

CERTIFIED EXPERT
Top Expert 2016
Commented:
This one is on us!
(Get your first solution completely free - no credit card required)
UNLOCK SOLUTION

Author

Commented:
>>><input type="checkbox"  name="region" value="region<%=j>" ............

what is     value="region<%=j>"    ??  why did you do that ?

 I just want to persist  checked/unchecked status of the checkboxes.  ....How value="region<%=j>"  can help at this part ?

Also I think you meant value="<%=region%><%=j>"    really .
CERTIFIED EXPERT
Top Expert 2016

Commented:
No. Each region must have a distinct value, but the same name

Author

Commented:
Ok .

>>>Each region must have a distinct value, but the same name

so, there is no harm if I do value="<%=region%><%=j>" . Note , there is a while loop for region.

By the way,  by values I actually meant the checked/unchecked status of the checkboxes .  I'm not interested  to save the field  value="<%=region%><%=j>" but I intend to save/retrieve the checked/unchecked status of the checkboxes  How do I do that here ?

CERTIFIED EXPERT
Top Expert 2016
Commented:
This one is on us!
(Get your first solution completely free - no credit card required)
UNLOCK SOLUTION

Author

Commented:
Ok . fine ...I just have gone through that  link
So, whatever the checkbox we select , only values of those checkboxes will go to the server.....fine.

But  how do we retrieve the checked status now ?

For example, if the user selected Cricket, Football, Tennis , then next time I have to show these checkboxes as checked.

how to do this part ?
CERTIFIED EXPERT
Top Expert 2016

Commented:
>>
For example, if the user selected Cricket, Football, Tennis , then next time I have to show these checkboxes as checked.

how to do this part ?
>>

That's up to you. You could  perhaps save them into a bean that holds the indexes of the checked ones
Mick BarryJava Developer
CERTIFIED EXPERT
Top Expert 2010
Commented:
This one is on us!
(Get your first solution completely free - no credit card required)
UNLOCK SOLUTION

Author

Commented:
Thanks for the comments. Here is the proposed retrieval code . I see a JSP syntax problem here .
 
Planned  code :
<%
// allCheckedvalues  is a List of checked values
%>
<input TYPE=checkbox NAME="region" VALUE="<%=region><%=j%>" <%if(<%if(allCheckedvalues.contains(<%=region%><%=j%>))
){out.print("checked");}%>>
Please look at  that bold part . Can we write that way inside contains method ? thats seems a JSP syntax problem. Could you please correct it ?

 
<%
// allCheckedvalues  is a List of checked values
%>
<input TYPE=checkbox NAME="region" VALUE="<%=region><%=j%>" <% if(allCheckedvalues.contains(region+j)) {out.print("checked");}%> >
can you post how you are iterating the object for loop
check this

<%
            List list= session.setAttribute("emp");

            for(int j=1;j<=list.size();j++)
            {
                  Region reg= (Region)list.get(j);
                  %>

      <input TYPE='checkbox' NAME="region" VALUE="<%=reg.getRegion()%><%=j%>" <% if(allCheckedvalues.contains(reg.getRegion()+j)) {out.print("checked");}%> >


            <%}

%>
CERTIFIED EXPERT
Top Expert 2016

Commented:
A form containing checkboxes would look something like
<form action="">
<%
	for (int j = 0;j < 20;j++) {
		String region = "region" + j;
%> <input type="checkbox" name="region" value="<%=region%>"
	<%=allCheckedvalues.contains(region) ? "checked" : ""%> /><br />
<%
	}
%>
</form>

Open in new window

Mick BarryJava Developer
CERTIFIED EXPERT
Top Expert 2010

Commented:
you don't need contains. simpler to just create an array containg the checked state of each checkbox. Makes the code much more readable.

<input TYPE=checkbox NAME="region" VALUE="<%=region%><%=j%>" <%= checked[j] >>

Author

Commented:
I am doing this way actually , Please see the code below for data binding to the check boxes.
too many brackets/scriplets ....not sure whether this would give a jsp compile error ....could you please check once whether code is perfect to work ?


Now,I will write the code in action class this way..

String[] checkedValues = req.getParameterValues("theatre");
String txtUserName=req.getParameter("txtUserName");

// UPDATE the DB with these checked values for this   txtUserName.
// IF UPDATE FAILS then do an INSERT


Do you see any chance to minimize the code ?





.....................
<div>
				<tr>
				<td><img src="images/closed.gif" alt="closed" onClick="expandCollapseFunc(this,'expCollapse<%=whilecounter%>','<%=theatre%>')"><b>&nbsp;&nbsp<%=theatre%></b></td>
				
				<%
				String sql = "SELECT checkedbox from MYAPPS_CHECKEDBOXES where guid='"+txtUserName+"'";
				
				Session hibernateSession = HibernateUtil.getSession();
				con = hibernateSession.connection();
				java.sql.Statement stmt=con.createStatement();
				ResultSet rs = stmt.executeQuery(sql);
				if(rs.next()){
						String [] checkedbox = rs.getString("checkedbox").split("\\,");
						java.util.ArrayList allCheckedBox= new ArrayList(Arrays.asList(checkedbox));
						for(int j=0;j<16;j++){ % > 
							
						<input type="checkbox"  class="selectColumn selectColumn<%=theatre%> Column<%=(j+2)%>"  name="theatre" value="<%=theatre><%=k>" align="middle" <%if(allCheckedBox.contains(theatre+k)){out.print("checked");}%>> 
						
							<% 
								k=k+1;
						
						}       %>
						
				}else{
				
				      for(int j=0;j<16;j++){ % > 
				
						<input type="checkbox"  class="selectColumn selectColumn<%=theatre%>   Column<%=(j+2)%>"  name="theatre"  value="<%=theatre><%=k>"  align="middle" />
					
					<% 
						k=k+1;
					 }
				  }
					%>

					<%
					if(rs!=null)rs.close();
					if(con!=null)con.close();
					if(hibernateSession!=null)hibernateSession.close();
					%>	
				
				</tr>
                </div>
.................................

Open in new window

Author

Commented:
>>>>simpler to just create an array containg the checked state of each checkbox.

where you want to create array containg the checked state of each checkbox.?  in JSP ?   but then it wont bind the data...it will init the array everytime when page loads.

please look at the code above . Thats what I'm planning to do  . Can it be made smaller and more readable  ?

I'm not getting you actually.  Could you please post what code should be in JSP  and what code will be in Action class ?

Do you see there is an opportunity to make my code smaller ?


whatever you are doing  is not correct way.follow this approach;In top.jsp am initializing the array and in that i am including an iframe which included another jsp index.jsp;

not not to init the array everytime when page loads i have initialized the array in top.jsp;

checked values will come in the Servlet ;see the code below;

run http://localhost:8080/context/top.jsp

top.jsp
***
<html>
  <head>
   
    <title>My JSP 'top.jsp' starting page</title>
   

<script>
var arr = new Array();

</script>
  </head>
 
  <body>
     <iframe src ="index.jsp" width="100%" height="300"  FRAMEBORDER="0" SCROLLING="no">
      <p>Your browser does not support iframes.</p>
    </iframe>
  </body>
</html>

index.jsp
*********
<script>
      
      function selected(obj)
      {
        parent.arr.push(obj.value);      
      }
      
      function ex()
      {

      document.frm.chkvalues.value=parent.arr.join(",");
      document.frm.action="http://localhost:8080/Iframe/TestServlet";
      document.frm.submit();
      }
      

      
      function loadSelectedData()
            {
                   var checkBoxObjs = document.getElementsByName("chk");
                   
                 
                    for(var j=0;j<parent.arr.length;j++)
                      {
                           var checkedValue =parent.arr[j];
                       
                        alert(checkedValue)
                        for(var i=0;i<checkBoxObjs.length;i++)
                           {

                                                var chkboxval = checkBoxObjs(i).value;



                                               if(chkboxval!=null)
                                               {
                                                 
                                                           
                                                               if(checkedValue == chkboxval)
                                                                 {
                                                                   checkBoxObjs.item(i).checked = true;
                                                                 }
                                                               
                                                }
                                           }
                                    
                                    
                                    }
                                    
                   }

      
      
      </script>

  </head>
 
  <body onload="loadSelectedData()">
  <form name="frm"  >
  <input type="checkbox" name="chk" value="a"  onClick="selected(this)"/>
  <input type="checkbox" name="chk" value="b" onClick="selected(this)"/>
  <input type="checkbox" name="chk" value="c" onClick="selected(this)"/>
 
       <input type="button" value="submit" onClick="ex();"/>
       <input type="hidden" name="chkvalues"/>

</form>
  </body>
</html>
TestServlet.java
*******************

public class TestServlet extends HttpServlet {

      public void doGet(HttpServletRequest request, HttpServletResponse response)
                  throws ServletException, IOException {

            response.setContentType("text/html");
            PrintWriter out = response.getWriter();
            
            String chkval = request.getParameter("chkvalues");
      
            System.out.println(chkval);
            
                  getServletContext().getRequestDispatcher("/index.jsp").forward(request,response);
      }
}
i have given some modifications for selected(obj) function.


function selected(obj)
	{
	  if(obj.checked)
	  {
	    parent.arr.push(obj.value);
	  }
	   else
        {
                    for(var i=0;i< parent.arr.length;i++)
                    {
                              var  data =  parent.arr[i];
                                
                                if(data!=null)
                                {
                            
                                            if(data==obj.value)
                                            {
														parent.arr.splice(i, 1);
                                                        break;
                                            }
                                }
                    }

             
        }	
	}

Open in new window

by this logic you can get the checked values in servlet and also you can maintain the checkbox status through out the pages.

Author

Commented:
CHEJ / OBJECTS , do you see any opportunity to improve the code I posted.

chaituu:  I can not use iframe's etc you posted  as this won't  fit in my system.  Its just a part of the big page where I'll be doing this stuff.

CERTIFIED EXPERT
Top Expert 2016

Commented:
You're using Hibernate but you seem only to be executing statements in a standard JDBC fashion. You should be using it to map the user's theatre preferences to a suitable bean that you can then manipulate in your jsp
Mick BarryJava Developer
CERTIFIED EXPERT
Top Expert 2010

Commented:
you can get rid of all that embedded java code, just makes it messy
i have modified your code.i think you wnt get compiled time errors in jsp;


<div>
				<tr>
				<td><img src="images/closed.gif" alt="closed" onClick="expandCollapseFunc(this,'expCollapse<%=whilecounter%>','<%=theatre%>')"><b>&nbsp;&nbsp<%=theatre%></b></td>
				
				<%
				String sql = "SELECT checkedbox from MYAPPS_CHECKEDBOXES where guid='"+txtUserName+"'";
				
				Session hibernateSession = HibernateUtil.getSession();
				con = hibernateSession.connection();
				java.sql.Statement stmt=con.createStatement();
				ResultSet rs = stmt.executeQuery(sql);
				if(rs.next()){
						String [] checkedbox = rs.getString("checkedbox").split("\\,");
						java.util.ArrayList allCheckedBox= new ArrayList(Arrays.asList(checkedbox));
						for(int j=0;j<16;j++){ %> 
							
						<input type="checkbox"  class="selectColumn<%=theatre%> Column<%=(j+2)%>"  name="theatre" value="<%=theatre><%=k%>" align="middle" <%if(allCheckedBox.contains(theatre+k)){out.print("checked");}%>> 
						
							<% 
								k=k+1;
						
						}      
						
				}else{
				
				      for(int j=0;j<16;j++){ %> 
				
						<input type="checkbox"  class="selectColumn selectColumn<%=theatre%>   Column<%=(j+2)%>"  name="theatre"  value="<%=theatre><%=k%>"  align="middle" />
					
					<% 
						k=k+1;
					 }
				  }
					%>

					<%
					if(rs!=null)rs.close();
					if(con!=null)con.close();
					if(hibernateSession!=null)hibernateSession.close();
					%>	
				
				</tr>
                </div>

Open in new window

Author

Commented:
I'm getting error at this part . Do you see any mistake at this part ?

<input type="checkbox" class="selectColumn<%=theatre%> Column<%=(j+2)%>" name="theatre" value="<%=theatre><%=k%>" align="middle" <%if(allCheckedBox.contains(theatre+k)){out.print("checked");}%>>
Error:   illegal start of expression
')' expected
 

<input type="checkbox" class="selectColumn selectColumn<%=theatre%> Column<%=(j+2)%>" name="theatre" value="<%=theatre><%=k%>" align="middle" />
<input type="checkbox" class="selectColumn selectColumn<%=theatre%> Column<%=(j+2)%>" name="theatre" value="<%=theatre><%=k%>" align="middle" />
Error:  ')' expected
illegal start of expression

<input type="checkbox" class="selectColumn<%=theatre%>" name="theatre" value="<%=theatre><%=k%>" align="middle" <%if(allCheckedBox.contains(theatre+k)){out.print("checked");}%>>

REMOVE  THIS PART Column<%=(j+2)%> and check ;

Author

Commented:
>>>REMOVE  THIS PART Column<%=(j+2)%> and check ;
I can not remove them . I need 3  CSS   CLASS  values there as shown in the code . I'm using JQuery which will use those  CLASS values.
I  want to remove the syntax errors  without loosing the any piece of code.
why i asked to remove is so that we will know where exactly problem is lying?

problem should be either in 2 areas.
1.Column<%=(j+2)%>
2.<%if(allCheckedBox.contains(theatre+k)){out.print("checked");}%>

first if u identify the problem then we will fix that problem
This one is on us!
(Get your first solution completely free - no credit card required)
UNLOCK SOLUTION

Author

Commented:
yea...I see that ...thanks.
Let me check it out ...will update you.
Unlock the solution to this question.
Join our community and discover your potential

Experts Exchange is the only place where you can interact directly with leading experts in the technology field. Become a member today and access the collective knowledge of thousands of technology experts.

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.