Tuesday, February 25, 2014

PHP form - remember input checkbox values




In PHP form, we may need to remember inpt checkbox values.  As checkbox has multiple choices,
the $_POST of the checkbox returns an array.  The checkbox name is also an array. We use in_array to check  if the return array contains the checkbox values.
Example as following:
<?php
if (($_SERVER['REQUEST_METHOD'] == 'POST') && (!empty($_POST['action']))):

 if (isset($_POST['favoritefood'])) { $favoritefood = $_POST['favoritefood']; }
 endif;
?>

 <form id="myform" name="testform"  action="<?php echo $_SERVER['PHP_SELF'] ?>" method="POST">
Favorite Food
                <ol>
                    <li>
                        <input type="checkbox" name="favoritefood[]" value="apple"   id="appleid"
                        <?php if ((isset($favoritefood)) && (in_array("apple", $favoritefood))) { echo "checked"; } ?> />
                        <label for="appleid">Apple</label>
                    </li>
                    <li>
      <input type="checkbox" name="favoritefood[]" value="orange"   id="orangeid"
                        <?php if ((isset($favoritefood)) && (in_array("orange", $favoritefood))) { echo "checked"; } ?> />
                        <label for="orangeid">Orange</label>          
                    </li>
                    <li>
                     <input type="checkbox" name="favoritefood[]" value="banana"   id="bananaid"
                        <?php if ((isset($favoritefood)) && (in_array("banana", $favoritefood))) { echo "checked"; } ?> />
                        <label for="bananaid">Banana</label>             
                    </li>
                </ol>

        <button type="submit" name="action" value="submit">send</button>
</form>

No comments:

Post a Comment