After successfully setting the checkbox to true by default, how do you handle the case of the checkbox being deselected when the user submits the form? Since HTML forms submit *no value* for an unselected checkbox, there is no "false" submitted to update the form; and the corresponding checkbox attribute remains true, even if the checkbox was deselected and *should* now be set to false.
Am I missing something here? Is there some workaround for this? I am aware of the "reset" method, but does setting the value to "false" there help in this case?
Joined: Feb 15, 2005
Your question is a good one. Checkboxes and radio buttons are tricky in that they don't return a value if unchecked. This fact is the main reason the reset() method was included as a part of the action form. In fact, resetting the value to false in the reset() method is the workaround for this. In the case at hand, putting the statement "setMarried(false);" in the reset() method for the form will ensure that the value is false if unchecked, and true if checked. If you have a group of checkboxes or radio buttons that return an array of values, the thing to do is set the String array to an empty array as in "setMaritalStatus(new String);"
Thanks for the feedback. I understand how to use reset() to set checkbox values to false unless checked on the form. However, the situation gets tricky if the checkbox should *default* to try (pre-checked on page load).
The only solution I found was:
- Use the reset() method to set the checkbox to "true". - In the jsp, include a hidden field with the same name as the checkbox property, and the value "false".
In this case, the checkbox will load as checked. The server will read the *first* value it finds for the property, and ignore subsequent values with t he same property name. So, if the checbox is still checked on submit, the "true" value will be read, and the following "false" from the hidden field will be ignored. If the checkbox is unchecked on submit, the hidden field with value "false" will be used to set the property.
This works in my environment. However, I'm not sure what specs say about behavior in the case of multiple values submitted for the same field, and this *may* vary by environment/container. So I'm not thrilled with this solution, either, but I can't find anything else that works better...