JSP Checkbox

JSP CheckBox is used to create a CheckBox in JSP.

JSP Checkbox

JSP Checkbox

In this tutorial you will learn how to create a checkbox using JSP. As we know, checkbox allows multiple selection at a time, but radio button allow only one selection at a time. So, when you need more than one selection always go for checkbox. Using the example we will try to understand how to create a checkbox in JSP. Now here is the example below:

Example : An example will explain you about how to use the checkbox. In this example we have created a JSP page named "CheckBox.jsp" then designed a form and put the checkboxes with various options and a submit button to submit the form. Then we have written JSP code using the Scriptlets to fetch the value of checked checkboxes. In this example for validation purpose, we have used JavaScript, to validate the form. If you will try to click on submit button without checking any checkbox then an alert box will be displayed with a message "Please select your subject". But when you will checked all checkboxes you will be displayed another alert box with message "Click Submit to Know your subject ". Then the subjects you have checked will be displayed however, a number of subject list will be displayed the number of checkboxes you have checked.

<%@ 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">
<script type="text/javascript">
function checkBox()
{
for(var i=0; i < document.form1.subject.length; i++)
{
if(!document.form1.subject[i].checked)
{
alert("Please Select Your Subject");
return false;
}
else
{
alert("Click Submit to Know your subject list");
return true;
}
}
}
</script>
<title>JSP Checkbox</title>
</head>
<body>
<form name="form1" onsubmit="checkBox()">
<h3>Please Select your Subject</h3>
<p><input type="checkbox" name="subject" value="Math"/>Math</p>
<p><input type="checkbox" name="subject" value="Science"/>Science</p>
<p><input type="checkbox" name="subject" value="Hindi"/>Hindi</p>
<p><input type="checkbox" name="subject" value="English"/>English</p>
<p><input type="checkbox" name="subject" value="Social Science"/>Social Science</p>
<p><input type="submit" value="submit" />
</form>
<%
String subject[]= request.getParameterValues("subject");
if(subject != null)
{
%>
<h4>You selected subject </h4>
<ul>
<%
for(int i=0; i<subject.length; i++)
{
%>
<li><%=subject[i]%></li>
<%
}
%>
</ul>
<%
}
%>
</body>
</html>

Output : After execution of the program, output will be look like as below :

Download Source Code