Java Script Select All CheckBox in a JSP

Consider a web page where you display a list of values in a tabular format. Assume that each row in that table has a check box either as a first or last element. You may be faced with a requirement to select/deselect all the check boxes. Use the following JSP code which uses java scrip to select/deselect check boxes.

<%@page import="java.util.List" %>

<%@page import="java.util.ArrayList" %>  

<%@ taglib uri="http://java.sun.com/jsp/jstl/core"  prefix="c" %>

<html>
<head>
<title>CheckBox Example</title>
</head>
<body>
<h1>CheckBox Example</h1>
<%
List langLst = new ArrayList();
langLst.add("Java");
langLst.add("C");
langLst.add("C++");
langLst.add("Small Talk");
langLst.add("C#");
request.setAttribute("langLst",langLst);
%>
<form>

<input type=checkbox name='selectAllCheck' onClick='javascript:funcSelectAll()' value='Select All'>Select All </input>
   
<TABLE border="1">
<tr>
      <th>
           <B>Programming Language List </B>
       </th>
</tr>

<c:forEach var="item" items="${requestScope.langLst}">
    <tr>
      <td>
           <input type=checkbox name='lang' ><c:out value="${item}" /> </input>
      </td>
    </tr>
</c:forEach>
</form>
</body>

<script language="javascript">
function funcSelectAll()
{
   if(document.forms[0].selectAllCheck.checked==true)
   {
            for (var a=0; a < document.forms[0].lang.length; a++)        {
                 document.forms[0].lang[a].checked = true;            
           }
     }
     else
     {
           for (var a=0; a < document.forms[0].lang.length; a++)        {
                  document.forms[0].lang[a].checked = false;          
           }
     }          

}
</script>
</html>

The above JSP code uses scriptlet code only for example purpose. In real world applications use either JSP standard tags or Expression language.

Technology: 

Search