Saturday, July 21, 2018

How to fetch values of check boxes from JSP

Please follow given guidelines before using these codes

1. Create two jsps inside Web Content folder (in your web-application). Names of jsp must be index.jsp and checkbox_demo.jsp

Note: In order to fetch the data of check boxes we need to use getParameterValues() method (This method belongs to HttpServletRequest interface). This methods takes name of check-boxes and returns an array of string (which is having values of check boxes).
We can use this method inside scriptlet tag in a JSP.

example >> String[] array = request.getParameterValues("name of check box");

<< code for index.jsp starts here >>

<%@ 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">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Home Page</title>
</head>
<body>
<fieldset>
<legend>Demo For Check boxes</legend>
<form action="checkbox_demo.jsp" method="post">
Area of Interest<br>
Java<input type="checkbox" name="choices" value="Java">
DBMS<input type="checkbox" name="choices" value="DBMS">
OS<input type="checkbox" name="choices" value="OS">
Testing<input type="checkbox" name="choices" value="Testing"><br>
<input type="submit" value="Test It">
</form>
</fieldset>
</body>
</html>

<< code for index.jsp ends here >>

<< code for checkbox_demo.jsp starts here >>

<%@ 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">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>checkbox_demo</title>
</head>
<body>
<center>
<%
// fetch the values associated with check boxes 
// using getParameterValues() method
// this method returns an array of string which stores
// the values of check boxes 
// note: if no check box is selected, this method will return null
// store array given by getParameterValues() method
String[] values = request.getParameterValues("choices");

// check if array has null
if(values == null)
{
out.println("<p>No selection found</p>");
}
else // if array has some values
{
// show values of array using for loop
out.println("<h3>you selected</h3>");
out.println("<ul>");
for(int i = 0; i < values.length; i++)
{
out.println("<li>");
out.println(values[i]);
out.println("</li>");
}
out.println("</ul>");
}
%>
</center>
</body>
</html>

<< code for checkbox_demo.jsp ends here >>

Output:






12 comments: