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.
Read now
Unlock full access