Skip to Main Content
Jakarta Struts Cookbook
book

Jakarta Struts Cookbook

by Bill Siggelkow
February 2005
Intermediate to advanced content levelIntermediate to advanced
528 pages
12h 53m
English
O'Reilly Media, Inc.
Content preview from Jakarta Struts Cookbook

3.12. Handling Unchecked Checkboxes

Problem

You need to ensure that a Boolean ActionForm property, corresponding to an HTML checkbox, is set to false when the checkbox is unchecked.

Solution

Create a checkbox input field that uses JavaScript to set the value of a hidden Boolean field. Use the logic:equal tag to set the checked property of the checkbox if the value for the hidden field is true. The JSP page (checkbox_test.jsp) in Example 3-18 uses this approach to guarantee a true or false value is always submitted.

Example 3-18. Guaranteeing checkbox settings

<%@ page contentType="text/html;charset=UTF-8" 
language="java" %>
<%@ taglib uri="http://jakarta.apache.org/struts/tags-html" 
prefix="html" %>
<%@ taglib uri="http://jakarta.apache.org/struts/tags-logic" 
prefix="logic" %>
<html>
<head>
  <title>Struts Cookbook - Chapter 4 : Checkbox Test</title>
</head>
<body>
  <html:form method="get" action="/ProcessCheckbox">
    <input type="checkbox" name="foo_"
      onclick="javascript:elements['foo'].value=this.checked;"
      <logic:equal name="CheckboxForm" property="foo" value="true"> 
        checked 
      </logic:equal>
    >
    <html:hidden property="foo"/>
    <html:submit/>
  </html:form>
</body>
</html>

Discussion

For such a common little field, the HTML checkbox can cause trouble. If a checkbox is unchecked and the form is submitted, no value for that field will be sent in the request. Suppose you have a form with one checkbox on it:

<html:form method="get" action="ProcessFoo"> <html:checkbox property="foo"/> <html:submit/> </html:form> ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Programming Jakarta Struts

Programming Jakarta Struts

Chuck Cavaness
Beginning Spring Framework 2

Beginning Spring Framework 2

Bruce Snyder, Sing Li, Anne Horton, Thomas Van de Velde, Naveen Balani, Christian Dupuis
Java Cookbook

Java Cookbook

Ian F. Darwin
Struts 2 in Action

Struts 2 in Action

J. Scott Stanlick, Chad Michael Davis, Donald J. Brown

Publisher Resources

ISBN: 059600771XSupplemental ContentErrata Page