HTML Checkboxes

Occasionally, you discover something that you have been doing wrong for a long time.  Sometimes it wasn’t something outright wrong but was just stupid.  That is what happened to me.

When using an HTML checkbox, it “POSTS” to the form submit page with the value of “on”.  I have always converted that on the page that accepts the form submission by something like this:
[code lang=”php”]if($_POST[‘checkbox’] == ‘on’)
$_POST[‘checkbox’] = 1;
}[/code] Or something like that.  And when there have been several checkboxes I have made several “if” statements like that.  This is needed when databasing a boolean value, which is 0 or 1, and the user chooses via checkbox.

Well, embarrassingly enough, there is a better way and it is much simpler.  From the HTML checkbox tag (<input type=’checkbox’ name=’my_checkbox’ />) simply add “value=’1′”.  Now it’s automatic.

To summarize:

[code lang=”html”]<form action=’submit.php’ method=’post’>
<input type=’checkbox’ name=’my_checkbox’ value=’1′ /> My Checkbox
<input type=’submit’ value=’ Submit ‘ />
</form>[/code] PHP:
[code lang=”php”]echo $_POST[‘my_checkbox’]; // echos 1[/code]

This site uses Akismet to reduce spam. Learn how your comment data is processed.