Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring form checkbox tag: why generate a hidden element?

Tags:

spring-mvc

I am using Spring MVC for a web application. On a form, I have

<form:checkbox path="agreeTerms" id="agreeTerms"/>

When the page is rendered, the following HTML is generated

<input id="agreeTerms" type="checkbox" value="true" name="agreeTerms">
<input type="hidden" value="on" name="_agreeTerms">

Does anyone know the purpose of the hidden tag? What would happen if the hidden input tag is removed?

Thanks!

like image 381
curious1 Avatar asked Jun 28 '13 15:06

curious1


1 Answers

The hidden input tag is to indicate a field that was originally part of the form. When a form is submitted the checkbox input field is only sent if it has a value (i.e. 'checked'). If it's not selected then nothing is sent. The underscore prefixed hidden field is using to indicate that it was part of the form but should be defaulted to "un-checked/false".

You can test this out by creating an HTML form with a checkbox field and submitting it without the field checked.

Also, to see how it's done check out the source code for WebDataBinder:

/**
* Check the given property values for field markers,
* i.e. for fields that start with the field marker prefix.
* <p>The existence of a field marker indicates that the specified
* field existed in the form. If the property values do not contain
* a corresponding field value, the field will be considered as empty
* and will be reset appropriately.
* @param mpvs the property values to be bound (can be modified)
* @see #getFieldMarkerPrefix
* @see #getEmptyValue(String, Class)
*/
like image 99
sehrope Avatar answered Oct 17 '22 14:10

sehrope