Check Boxes

A check box is another control that, like a text field, is created in HTML using the <input> element. It provides a single box that can be ticked or not, depending on the option chosen. It doesn't require any data from the user, other than a click in the check box, so any data this control contains is quite different from the text field. In HTML it looks very similar—the only difference is the type:

<input name="Choice" type="checkbox">

A check box is appropriate when you have a question that requires a strict yes/no answer. Check boxes also have a checked attribute, which takes no value. Supply this attribute in the control and the check box will be checked by default:

<input name="Choice" type="checkbox" checked>

The control also has a value attribute set to on by default.

Some of the advantages of check boxes over other forms of input control aren't immediately obvious, but they become clear after you've used several of them. The following exercise utilizes just one check box and returns the contents of it to the screen.

Try it Out: Use a Check Box

Start Example:
  1. In you Web page editor type the following code:

    <html>
    <head><title></title></head>
    <body>
    <form method=" POST" action=" checkbox.php">
    Have you ever eaten haggis before?
    <input name="Choice" type="checkbox">
    <br>
    <br>
    <Input type="submit" value="Submit">
    </form>
    </body>
    </html>
    
  2. Save it as checkbox.html, and close the file

  3. Start a new file and type in the following:

    <html>
    <head><title></title></head>
    <body>
    <?php
    echo $_POST['Choice'];
    ?>
    </body>
    </html>
    
  4. Save it as checkbox.php, and close the file.

  5. Open checkbox.html in your browser and check the check box.

  6. Click Submit. The choice echoed out is "on,".

  7. Click your browser's Back button, uncheck the check box, and click Submit again. Because the box was unchecked this time, nothing shows up in the browser.

How it Works

Again, there's no query string on the end of the URL because you used the POST method to pass your form information to the Web server. You set this in the first of the two programs, checkbox.html:

<html>
<head><title></title></head>
<body>
<form method="POST" action="checkbox.php">

The check box form control is created with the <input> element:

Have you ever eaten haggis before?
<input name="Choice" type="checkbox">

In checkbox.php, you call the PHP variable, which has exactly the same name as the control you set in checkbox.html:

<?php
echo $_POST['Choice'];
?>

The only difference is that the variable is now created with a value that wasn't assigned by you. If the check box was ticked by the user, then it contains the value on. If it wasn't, then it contains nothing at all.