Default values for HTML checkboxes

So this is a little tip that looking back on is so obvious it pains me to even write about it. However I’m sure I’m not the only one who has encountered this issue, and so I’m posting it here in the hope that it may help someone like myself.The issue is to do with HTML checkboxes. It is obviously easy to set a value for when these are checked that gets sent to the server on form submission. But for years I never knew how to specify a default value that gets passed to the server when the checkbox is not checked.Until the other day I always used PHP to check for the presence of the checkbox name in the POST array, and if it was not present I was then specifying the default value in there.

However, I’ve always felt that there should be some way to specify this in the HTML – an attribute perhaps – on the checkbox input element where you could specify the unchecked value. But unfortunately that attribute doesn’t exist. What I stumbled upon the other day, however, is a different way to achieve the same result – and it’s ridiculously easy.

The way to do it is to have a hidden input element before the checkbox, with the same name and the value attribute set to the value you wish the checkbox to default to when unchecked. That’s it! So basically your html would look like this:

<input type="hidden" name="checkbox_name" value="unchecked_value" />
<input type="checkbox" name="checkbox_name" value="checked_value" />

When the checkbox is submitted without a value, that input does not get passed to the server. Instead the value of the hidden input gets submitted. However, when the checkbox is ticked, the value of the hidden field is overwritten so the server-side code receives only the checkbox value. Pretty sweet, and as a added bonus it is also perfectly valid XHTML 1.0 / HTML 4.01 Strict.

There is only one caveat – it won’t work when you are assigning input names as an array such as my_input_name[]. There is no way to get around this as far as I know, unless in your page you are able to explicitly assign the array key numbers in the for each input like so:

<input type="text" name="my_input_name[0]" value="item_value" />
<input type="hidden" name="my_input_name[1]" value="unchecked_value" />
<input type="checkbox" name="my_input_name[1]" value="checked_value" />

So whilst it will not work in 100% of the cases, I think this a pretty useful and easy to implement way to set unchecked values for checkboxes.

Source: Allmarkedup.com

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s