Re: Unknown number of check boxes?

From: Date: Mon, 28 May 2007 19:55:49 +0000
Subject: Re: Unknown number of check boxes?
Groups: php.general 
Request: Send a blank email to php-general+get-255720@lists.php.net to get a copy of this message
Stephen Neigaard wrote:
I would like to have a unknown number of generated check boxes like this: <input type="checkbox" name="chk01" /> <input type="checkbox" name="chk02" /> <input type="checkbox" name="chk0X" /> And the name will be generated "chk01 to chk99", but how do I make the receiving PHP script that "scans" for post variables that are sent, so that I can work on this information?
Inspect this code example to see a way to handle this problem using magic form variables in contained POST arrays: <code> <h4>Test of Multiple Checkboxes</h4> <form method="post" action="<?php echo($_SERVER['PHP_SELF']); ?>"> <?php function getCheckboxes() { for ($i = 100; $i > 0; $i--) {
       $tr = $i % 5 === 0 ? Array('','') : Array('<tr>','</tr>');
       $str .= "<label><input type=\"checkbox\" " .
               "name=\"form[checks][]\" value=\"$i\" /> Input
#$i</label>\n"; } return $str; } echo(getCheckBoxes()); ?> <p><input type="submit" /></p> </form> <hr /> <pre> <?php if (!empty($_POST)) { print_r($_POST); } ?> </pre> <h4>Consuming of form post</h4> <p>An example of inverting a posted checkbox array to support $checked[45] === true behavior, making it easier to access and test the posted content</p> <pre> <?php // This will return an array that has inverted the posted // items that were in checkboxes and had a state of // checked=true function consumeFormChecks($arr) { $consume = Array(); for ($i = 0; $i < count($arr); $i++) {
       $consume[$arr[$i]] = true;
} return $consume; } if (!empty($_POST)) { print_r(consumeFormChecks($_POST['form']['checks'])); }else { echo('<h4>Please select some random checkboxes above' .
        ' and submit the form</h4>');
} ?> </pre> </code> -- Jared Farrish Intermediate Web Developer Denton, Tx Abraham Maslow: "If the only tool you have is a hammer, you tend to see every problem as a nail." $$

« previous php.general (#255720) next »