Solved

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

Posted on 2015-02-16
7
497 Views
Last Modified: 2015-02-17
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
Comment
Question by:Pradip Shenolkar
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 4
  • 2
7 Comments
 
LVL 38

Expert Comment

by:Tom Beck
ID: 40612097
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
 
LVL 27

Expert Comment

by:rrz
ID: 40612463
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
 

Author Comment

by:Pradip Shenolkar
ID: 40612484
@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
PeopleSoft Has Never Been Easier

PeopleSoft Adoption Made Smooth & Simple!

On-The-Job Training Is made Intuitive & Easy With WalkMe's On-Screen Guidance Tool.  Claim Your Free WalkMe Account Now

 
LVL 27

Expert Comment

by:rrz
ID: 40612602
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
 
LVL 27

Accepted Solution

by:
rrz earned 500 total points
ID: 40613572
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
 
LVL 27

Expert Comment

by:rrz
ID: 40614577
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
 

Author Closing Comment

by:Pradip Shenolkar
ID: 40614582
Thanks alot..
It works.
0

Featured Post

Get 15 Days FREE Full-Featured Trial

Benefit from a mission critical IT monitoring with Monitis Premium or get it FREE for your entry level monitoring needs.
-Over 200,000 users
-More than 300,000 websites monitored
-Used in 197 countries
-Recommended by 98% of users

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Introduction HTML checkboxes provide the perfect way for a web developer to receive client input when the client's options might be none, one or many.  But the PHP code for processing the checkboxes can be confusing at first.  What if a checkbox is…
This article discusses how to implement server side field validation and display customized error messages to the client.
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

690 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question