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
430 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
  • 4
  • 2
7 Comments
 
LVL 38

Expert Comment

by:Tom Beck
Comment Utility
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
Comment Utility
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
Comment Utility
@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
Do You Know the 4 Main Threat Actor Types?

Do you know the main threat actor types? Most attackers fall into one of four categories, each with their own favored tactics, techniques, and procedures.

 
LVL 27

Expert Comment

by:rrz
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
Thanks alot..
It works.
0

Featured Post

Free Trending Threat Insights Every Day

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

Avoid defining the variables in the global scope; trying to define them in a local function scope. Because:   • Look-up is performed every time a variable is accessed.   • Variables are resolved backwards from most specific to least specific scope…
This article demonstrates how to create a simple responsive confirmation dialog with Ok and Cancel buttons using HTML, CSS, jQuery and Promises
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…

772 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

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now