faqts : Computers : Programming : Languages : PHP : Common Problems : Forms and User Input

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

102 of 131 people (78%) answered Yes
Recently 5 of 10 people (50%) answered Yes

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