• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 589
  • Last Modified:

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

0
Pradip Shenolkar
Asked:
Pradip Shenolkar
  • 4
  • 2
1 Solution
 
Tom BeckCommented:
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>
0
 
rrzCommented:
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?
0
 
Pradip ShenolkarAuthor Commented:
@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

0
Never miss a deadline with monday.com

The revolutionary project management tool is here!   Plan visually with a single glance and make sure your projects get done.

 
rrzCommented:
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.
0
 
rrzCommented:
Please try this code.
<%@ 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);
%>
<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>
<%
  String clientChecked[]= request.getParameterValues(categoryDatabase);
  String checkedString = "";
  if(clientChecked != null)
  {  
    out.print("<h4>I like most " + categoryDatabase + "s</h4><ul>");
    for(int i=0; i< clientChecked.length; i++)
    {
	    checkedString += clientChecked[i];
        out.print("<li>" + clientChecked[i] + "</li>");
    }
     out.print("</ul>");
  }
  pageContext.setAttribute("checkedString", checkedString);
%>
<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

0
 
rrzCommented:
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

0
 
Pradip ShenolkarAuthor Commented:
Thanks alot..
It works.
0

Featured Post

The new generation of project management tools

With monday.com’s project management tool, you can see what everyone on your team is working in a single glance. Its intuitive dashboards are customizable, so you can create systems that work for you.

  • 4
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now