Link to home
Start Free TrialLog in
Avatar of Pradip Shenolkar
Pradip ShenolkarFlag for India

asked on

How to retain state of dynamically created, multiple checked checkboxes after submitting the form to same page in jsp and javascript ?

When I check few checkboxes and submit the form the state of checkboxes is retained.
(This code is from Expert rrz)
Assuming that in this code, checkboxes are created dynamically and values of checkboxes are loaded dynamically  how can I achieve the same thing.


<%@ page import="java.util.*" %>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%
  String checkString = "";
  String fruits[]= request.getParameterValues("fruit");
  if(fruits != null)
  {
    List list = Arrays.asList(fruits);
	if(list.contains("Mango"))checkString += "document.form1.fruit[0].checked=true;";
    if(list.contains("Apple"))checkString += "document.form1.fruit[1].checked=true; ";	
	if(list.contains("Grapes"))checkString += "document.form1.fruit[2].checked=true; ";
	if(list.contains("Papaya"))checkString += "document.form1.fruit[3].checked=true; ";
	if(list.contains("Lychee"))checkString += "document.form1.fruit[4].checked=true; ";
	if(list.contains("Pineapple"))checkString += "document.form1.fruit[5].checked=true; ";		  
    out.print("<h4>I like most fruits</h4><ul>");
    for(int i=0; i<fruits.length; i++)
    {
        out.print("<li>" + fruits[i] + "</li>");
    }
     out.print("</ul>");
  }
%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<script type="text/javascript">
function check()
{
   <%=checkString%> 
}
var flag=0;
function checkBoxValidation()
{
    for(var i=0; i < document.form1.fruit.length; i++)
    {
        if(document.form1.fruit[i].checked)
        {
            flag++;
        }
    }
    if(flag==0)
	{
	    alert("select something");
	}
}
</script>
<title>JSP Multiple Checkbox</title>
</head>
<body onload="check();">
<form name="form1" onsubmit="checkBoxValidation()">
<h3>Select your favorite Fruits</h3>
<p><input type="checkbox" name="fruit" value="Mango" />Mango</p>
<p><input type="checkbox" name="fruit" value="Apple" />Apple</p>
<p><input type="checkbox" name="fruit" value="Grapes" />Grapes</p>
<p><input type="checkbox" name="fruit" value="Papaya" />Papaya</p>
<p><input type="checkbox" name="fruit" value="Lychee" />Lychee</p>
<p><input type="checkbox" name="fruit" value="Pineapple" />Pineapple</p>
<p><input type="submit" value="submit" />
</form>
</body>
</html>
                                          

Open in new window

Avatar of Tom Beck
Tom Beck
Flag of United States of America image

I cannot help with the Java side but if you submit common checkbox names as an array, you can determine from the posted data which ones were checked. Only those checked will be included in the post. It would be a simple matter then to re-check them as they are re-created in the loop and added to the response. (I'm assuming the form submission method is "post", but it can work with "get" too.)

<form name="form1" onsubmit="checkBoxValidation()" method="post">
<p><input type="checkbox" name="fruit[]" value="Mango" />Mango</p>
<p><input type="checkbox" name="fruit[]" value="Apple" />Apple</p>
<p><input type="checkbox" name="fruit[]" value="Grapes" />Grapes</p>
<p><input type="checkbox" name="fruit[]" value="Papaya" />Papaya</p>
<p><input type="checkbox" name="fruit[]" value="Lychee" />Lychee</p>
<p><input type="checkbox" name="fruit[]" value="Pineapple" />Pineapple</p>
What is the source of the data?  Do want the client to enter a name and a list of values for the checkboxes? Or will the list come from somewhere on the server?
Avatar of Pradip Shenolkar

ASKER

@rrz : list of values will be fetched from database (using java bean class),

As an example here is a code.
I know you won't be able to execute this code but I have provided it so that you can get some idea.


<div>
<c:forEach var="i" begin="0" end="<%=c1.getDimensions().size()-1%>" step="1">
   <input type="checkbox" name="selected_dims" value="${c1.getDimensions().get(i).getName()}"><c:out value="${c1.getDimensions().get(i).getName()}"/>
</c:forEach>
   </div>

Open in new window

Ok, thanks for the specification. I am glad to see that you are using JSTL. I am busy today. I'll try to get to this in 8 to 12 hours.
ASKER CERTIFIED SOLUTION
Avatar of rrz
rrz
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
I did more work on this. Please try this code. The use of scriptlets should be kept to a minimum.
<%@ page import="java.util.*" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<%
  String categoryDatabase = "fruit";
  List listDatabase = Arrays.asList("Mango","Apple","Grapes","Papaya","Lychee","Pineapple");
  pageContext.setAttribute("category", categoryDatabase);  
  pageContext.setAttribute("list", listDatabase);
  String clientChecked[]= request.getParameterValues(categoryDatabase);
  String checkedString = "";
  if(clientChecked != null)
  {
    for(int i=0; i< clientChecked.length; i++)checkedString += clientChecked[i];
  }
  pageContext.setAttribute("checkedString", checkedString);
%>
<html>
   <head>
    <script language="Javascript">
        var flag=0;
        function checkBoxValidation()
        {
            for(var i=0; i < document.form1.${category}.length; i++)
            {
                if(document.form1.${category}[i].checked)
                {
                    flag++;
                }
            }
            if(flag==0)
	        {
	            alert("Select something.");
	        }
        }
    </script>
    </head>
 <body>
    <h4>I like most ${category}s</h4><ul>
    <c:forEach var="current" items="${paramValues[category]}">
        <li>${current}</li>
    </c:forEach>
    </ul>
<form name="form1" onsubmit="checkBoxValidation()">
<h3>Select your favorite ${category}s</h3>
<c:forEach var="current" items="${list}">
    <p><input type="checkbox" name="${category}" value="${current}" 
    <c:if test='${fn:contains(checkedString, current)}'>checked='checked'</c:if>/>${current}</p>
</c:forEach>
<input type="submit" value="submit" />
</form>
 </body>
</html>

Open in new window

Thanks alot..
It works.