Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 123
  • Last Modified:

Why the checkbox state is not retained in following code ?

When I check few checkboxes and submit the form, all checkboxes are set to unchecked state.
What am I doing wrong ?

<%@ 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 fruits[]= request.getParameterValues("fruit");
pageContext.setAttribute("fruits", fruits);
if(fruits != null)
{
%>
<h4>I likes fruit/s mostly</h4>
<ul>
<%
for(int i=0; i<fruits.length; i++)
{
%>
<li><%=fruits[i]%></li>
<%
}
%>
</ul>
<%
}
%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<script type="text/javascript">
var flag=0;
function checkBoxValidation()
{
for(var i=0; i < document.form1.fruit.length; i++)
{
if(document.form1.fruit[i].checked)
{
	document.form1.fruit[i].checked=true;
flag++;
}
}

if(flag==0)
	{
	alert("select smthing");
	}
	
}
</script>
<title>JSP Multiple Checkbox</title>
</head>
<body>
<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
2 Solutions
 
Jeffrey Dake Senior Director of TechnologyCommented:
You are harvesting the values, but when writing out your checkboxes you don't check if that value was submitted and setting the checkbox attribute of checked.  You should have a loop similar to the top checking if the array of fruits contains the checkbox you are displaying and add checked attribute if it does.
0
 
Tom BeckCommented:
Common checkbox names need to be submitted as an array.

<p><input type="checkbox" name="fruit[]" value="Mango"/>Mango</p>
<p><input type="checkbox" name="fruit[]" value="Apple"/>Apple</p>
...

Otherwise only the last one checked will come through on submit.
0

Featured Post

New feature and membership benefit!

New feature! Upgrade and increase expert visibility of your issues with Priority Questions.

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