<

Common Sense Examples Using Checkboxes with HTML, JavaScript and PHP

Published on
39,300 Points
19,000 Views
8 Endorsements
Last Modified:
Introduction
HTML checkboxes provide the perfect way for a web developer to receive client input when the client's options might be none, one or many.  But the PHP code for processing the checkboxes can be confusing at first.  What if a checkbox is not checked?  Unlike the text-type input controls, the unchecked checkbox is simply absent from the request.  This situation makes it necessary for our action script to know in advance what checkboxes might or might not be present.  What if we have several checkboxes that are related and we want an all-or-nothing option?  We can use an array of checkboxes and a little JavaScript to make our forms easier for the client.  This script demonstrates some of the popular design patterns for using checkboxes in HTML, JavaScript and PHP.  

Initialization
In the code example, script initialization starts at line 10.  We set up an associative array of key=>value pairs.  This array is our data model.  It lets the script produce checkboxes that are generated dynamically, depending on the contents of the array.  If you wanted to add, for example, "Graduates" you just add that to the $options array following the pattern shown in the code snippet.  No other changes to either the form or action script would be needed.  The new option would appear automatically.  If you think creatively about this array you realize that it does not need to be hard-coded.  It might come from the results of a data base query.

The "Action" Script
The action script is the next part of this code snippet.  It starts on line 20.  If the submit button was fired, we examine our array of options (line 25) and if the option was set in the $_POST["choice"] variable we set the value in $options to checked.  This strategy accomplishes two things for us.  First, it adds a measure of security to our application because we do not make any decisions based solely on the contents of the $_POST array.  The external data must match our internal data model or else it will be ignored, thus we have reduced the risk of an attack vector in the external data.  Second, it lets us remember the status of the checkboxes from one instance of the form to the next.

The action script is completed at line 35.  Obviously the action script could have done something a lot more interesting than just report and remember the checkbox selections.  For example, it could have used a data base to generate a list of grade-appropriate text books.  That part of the action script would happen near line 29.

The "Form" Script
The first part of the form script starts at line 39 with a "heredoc" definition that creates an HTML string.  It contains some JavaScript to give us the "toggle all" capability.  And it defines the top of the.  It ends at line 54.

The second part of the form is generated dynamically from the $options array (lines 57-74).  We use the contents of the $options array to create the input checkbox controls.  This design exploits the key=>value pairs of the PHP associative array to remember what was checked in the last submission of the form.

At line 77 we add the submit button and close the form, then we write the HTML string to the browser on the last line of the script.

The JavaScript
In PHP action scripts the $_POST variable is always an associative array, and in this example one element of that array, $_POST["choice"], is also an associative array.  Could we have had separate $_POST checkbox controls for each of Freshman, Sophomore, Junior and Senior?  Yes, of course.  But by grouping these choices into a sub-array of the $_POST array we enable the JavaScript that gives us the all-or-nothing toggle.  That JavaScript is a generalized black-box function (lines 41-48).  It takes three arguments.  The first two specify the form name ("checkForm") and the array name ("choice").  Because we could have multiple forms and/or multiple arrays of checkboxes on the same HTML page, this one JavaScript function will suffice to produce any number of toggle-all checkboxes that can be inserted into different forms and/or different groups of checkboxes.

Try It!
You can install this script as-is and run it to see the moving parts.
 
<?php // demo/EE_checkbox_demo.php
error_reporting(E_ALL);
echo "<pre>" . PHP_EOL;


// DEMONSTRATE HOW TO SUBMIT AND PROCESS CHECKBOXES


// THESE ARE THE NAMES OF THE CHECKBOXES
$options
= array
( 'Freshman'  => NULL
, 'Sophomore' => NULL
, 'Junior'    => NULL
, 'Senior'    => NULL
)
;

// IF THE FORM HAS BEEN SUBMITTED
if (!empty($_POST["sb"]))
{
    echo "CHOICES:";

    // SHOW THE CHOICES THAT WERE SELECTED
    foreach ($options as $opt => $status)
    {
        if (isset($_POST["choice"][$opt]))
        {
            // THIS IS WHERE YOU MIGHT DO THE PROCESSING FOR THE SELECTED CHOICE
            $options[$opt] = " checked ";
            echo PHP_EOL . $opt;
        }
    }
}
// END OF PHP PROCESSING - USE HTML AND JAVASCRIPT TO PUT UP THE FORM


// THE FIRST PART OF THE HTML DEFINED IN HEREDOC NOTATION
$html = <<<ENDHTML
<script language="JavaScript">
function toggle(formName, arrayName, YesNo)
{
    var xbox=document.getElementsByName(formName)[0].getElementsByTagName('input');
    for(i=0; i<xbox.length; i++)
    {
        if (xbox[i].name.substr(0,arrayName.length) == arrayName) xbox[i].checked=YesNo;
    }
}
</script>

<form method="post" name="checkForm">
<input type="checkbox" onClick="toggle('checkForm', 'choice', this.checked)"> TOGGLE ALL OR SELECT A GRADE:

ENDHTML;

// THE SECOND PART OF THE HTML CREATED DYNAMICALLY FROM $options
foreach ($options as $opt => $status)
{
    $html
    .= '<input'          // START THE INPUT CONTROL TAG
    . ' name="choice'    // ASSIGN THE NAME AS AN ARRAY [choice][]
    . '['                // USE BRACKET NOTATION
    . $opt               // THE ARRAY KEY
    . ']'                // CLOSE THE ARRAY BRACKET NOTATION
    . '" '               // CLOSE THE NAME ATTRIBUTE
    . ' type="checkbox"' // THE INPUT CONTROL TYPE ATTRIBUTE
    . ' value="'         // THE VALUE ATTRIBUTE
    . $opt               // THE NAME OF THE CHOICE
    . '" '               // CLOSE THE VALUE ATTRIBUTE
    . $status            // CHECKED OR NULL
    . " /> $opt"         // TEXT FOR THE CLIENT TO SEE
    . PHP_EOL
    ;
}

// ADD THE END OF THE DOCUMENT
$html .= '<input name="sb" type="submit" value="MAKE SELECTION" />' . PHP_EOL;
$html .= '</form>' . PHP_EOL;

// WRITE THE FORM
echo $html;

Open in new window

What Just Happened?
What have we accomplished with this script?  We have given the client the convenience of a checkbox-enabled web page.  We have made it easy to choose "all or nothing" as well as individual choices.  We have used a design that does not depend on external input in any unreasonable way (in other words, we accept only known good values in the $_POST array).  And we have created a design that is easy to modify or extend to other use cases.

Another Take on Unchecked Checkboxes
A frequent question is, "How do I get a default value for a checkbox?"  You can use a combination of form input controls to accomplish this. Create an input control with an attribute of type=hidden and a name attribute that is the same as the name attribute of your checkbox.  Place this input control into the HTML form immediately before the checkbox.  The hidden value will be transmitted if the checkbox is not checked.  But if the checkbox is checked, its name:value pair will cause it to override the hidden value in the request array.  This is not completely secure; you still have to filter / validate / sanitize the external input, but it goes a long way toward solving a common problem.
 
<?php // demo/unchecked_checkbox.php
error_reporting(E_ALL);

// SHOW HOW TO USE HIDDEN INPUT TO APPLY A VALUE TO AN UNCHECKED CHECKBOX

// SHOW THE POST ARRAY, IF ANY
if (!empty($_POST)) print_r($_POST);

// CREATE THE FORM USING HEREDOC NOTATION
$form = <<<ENDFORM
<form method="post">
<input type="hidden"   name="my_check_box" value="You Did Not Check It" />
<input type="checkbox" name="my_check_box" value="You Checked It" /> TRY CHECKING OR UNCHECKING THIS BOX
<input type="submit" />
</form>
ENDFORM;

echo $form;

Open in new window

To Learn More
Some further reading on PHP and forms is available here:
http://php.net/manual/en/language.variables.external.php
http://php.net/manual/en/reserved.variables.post.php
http://php.net/manual/en/tutorial.forms.php

Although it was not needed in our article here, this function is important when a script sends external input back to the client browser:
http://php.net/manual/en/function.htmlspecialchars.php

The very useful heredoc notation is described here.  It makes templates drop-dead simple in PHP:
http://php.net/manual/en/language.types.string.php#language.types.string.syntax.heredoc

Please give us your feedback!
If you found this article helpful, please click the "thumb's up" button below. Doing so lets the E-E community know what is valuable for E-E members and helps provide direction for future articles.  If you have questions or comments, please add them.  Thanks!

 
8
Comment
Author:Ray Paseur
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
0 Comments

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Join & Write a Comment

The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…
The viewer will learn the benefit of using external CSS files and the relationship between class and ID selectors. Create your external css file by saving it as style.css then set up your style tags: (CODE) Reference the nav tag and set your prop…

Keep in touch with Experts Exchange

Tech news and trends delivered to your inbox every month