This article demonstrates how to get checkbox value(s) from a HTML form to a JSP page. It consists of one HTML page 'sports.html', and one JSP page 'sports.jsp'.
In order to complete the example application, you should be familiar with the following:
JSP page 'sports.jsp' is also very simple. As user may select multiple checkboxes, so to get these multiple values for sports, a string array 'sports[]' is declared. Please note request.getParameterValues() is used to fetch values from checkboxes checked or selected. Now, array 'sports' consists of values for sports which user has selected as favorites. A loop is used to display the favorite sport(s) of user.
If user has selected Cricket, Football, Tennis, then output will be shown as:
Prerequisites
In order to complete the example application, you should be familiar with the following:
- HTML
- Java
- JSP
- Server such as Apache tomcat, J2EE, JBoss or other
- Sun JDK version 1.5 or above
HTML form: sports.html
Code: HTML
<HTML>
<body>
<FORM method="POST" ACTION="sports.jsp">
<center>
Select your favorite sport(s): <br><br>
<table>
<tr>
<td>
<input TYPE=checkbox name=sports VALUE=Cricket>
</td>
<td>
Cricket
</td>
</tr>
<tr>
<td>
<input TYPE=checkbox name=sports VALUE=Football>
</td>
<td>
Football
</td>
</tr>
<tr>
<td>
<input TYPE=checkbox name=sports VALUE=Tennis>
</td>
<td>
Tennis
</td>
</tr>
<tr>
<td>
<input TYPE=checkbox name=sports VALUE=Rugby>
</td>
<td>
Rugby
</td>
</tr>
<tr>
<td>
<input TYPE=checkbox name=sports VALUE=Basketball>
</td>
<td>
Basketball
</td>
</tr>
</table>
<br> <INPUT TYPE=submit name=submit Value="Submit">
</center>
</FORM>
</BODY>
</HTML>
JSP page: sports.jsp
Code: Java
<html>
<body>
<%! String[] sports; %>
<center>You have selected:
<%
sports = request.getParameterValues("sports");
if (sports != null)
{
for (int i = 0; i < sports.length; i++)
{
out.println ("<b>"+sports[i]+"<b>");
}
}
else out.println ("<b>none<b>");
%>
</center>
</body>
</html>
Code:
You have selected: Cricket Football Tennis
