Entry
How can I handle unselected checkboxes in PHP scripts?
How can I give unselected checkboxes a value?
Aug 31st, 2000 17:30
Rey Nuņez, Nathan Wallace, Ben Udall, Torben Wilson
In PHP you can handle empty checkboxes like this:
<?php
if ( empty( $checkbox ) ) {
$checkbox = 'N';
}
?>
Another way would be to have a hidden variable with the same name and a
default value in the form *before* the checkbox in question. That way,
if the checkbox is checked, its value will take precedence since it
comes later in the form; otherwise, the default hidden value will be
used.
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML-3.2//EN">
<html>
<head>
<title></title>
</head>
<body>
<form action="<?php echo $PHP_SELF ?>" method="post">
<input type="hidden" name="cbox[0]" value="no">
<input type="checkbox" name="cbox[0]" value="yes"> Checkbox<br>
<input type="submit" name="submitted" value="Submit"><br>
</form>
<?php
// first a test to make sure the form was submitted
if ( !empty( $submitted ) ) {
echo $cbox[0];
}
?>
<hr>
</body>
</html>
_____________________
If you meant having a checkbox initially checked by default, you can
simply use the HTML checked attribute:
<input type="checkbox" checked>Add me to list<br>
<input type="checkbox">Give me money too