Usually, if one sets the value of a checkbox to say 1, most browsers will post a key value pair with the value equal to 1 when the box is checked, but leave the key-value pair out when the box is unchecked.

Today I found a totally brilliant and obvious (but only in hindsight) way to get a value posted by a form for a checkbox when it is not ticked. This will allow e.g. a zero to be posted if unticked and a 1 if ticked.

Full article is at:
https://iamcam.wordpress.com/2008/01/15/unchecked-checkbox-values/

Simply create a hidden field with the same name directly before the checkbox, with a value of zero.

This exploits the property of browsers resolving the conflict that is multiple inputs of the same name, by submitting the last one i.e. each overwrites or updates the value much like assigning values to variables in any programming language.

<input name="vip" type="hidden" value="0">
<input name="vip" type="checkbox" value="1">

Leave a Reply

Your email address will not be published.