swape.net alireza balouch

17Apr/080

Checkbox value

When you post a form with checkbox it dose not return any value when the checkbox is not ticked.
This is something that should have been fixed a long time ago.
But for now here is the solution:

  1. <form action="?" method="post">
  2. <input name="myCheckbox" type="hidden" value="0" />
  3. <input name="myCheckbox" type="checkbox" />
  4. </form>

You put an hidden input before checkbox input with the same name.
Since the last checkbox overwrite the value when it is checked, the hidden input do not return "0" but when the checkbox is not checked, the hidden input with the same name returns a "0".

So when the checkbox is checked it returns "on" and when it is not checked it returns "0"

And to make it easier to click on the ckeckbox use "label" tag around the name.

Before:

My Checkbox

After:

This way you can click on the checkbox label and make it checked.
The correct way to write an checkbox checked from the start is like this:

  1. <input checked="checked" name="myCheckbox" type="checkbox" />
  2. My Checkbox
  3. </label>
Tagged as: , Leave a comment
blog comments powered by Disqus