Working with forms in PHP - Checkboxes
(Page 4 of 7 )
Now let's take a look at checkboxes. First a very simple checkbox situation - just a single checkbox. In form.html, after the line:
Fill in the text box: <INPUT type="text" name="mytextbox" size="20"><BR> |
add this line:
Check me or not: <INPUT type="checkbox" name="mycheckbox" value="1"><BR> |
In form.php after the line:
echo "<BR>You typed <b>" . $_POST['mytextbox'] . "</b> in the textbox.\n"; |
add the lines:
if(isset($_POST['mycheckbox'])) { echo "<BR>You checked the checkbox.\n"; } else { echo "<BR>You didn't check the checkbox.\n"; } |
Ok, that was a very simple checkbox example, let's do something with multiple checkboxes. In form.html, change the line:
Check me or not: <INPUT type="checkbox" name="mycheckbox" value="1"><BR> |
to read:
Check me or not: <INPUT type="checkbox" name="mycheckbox[]" value="1"><BR> |
Notice we have added opening and closing brackets [] to the name of the checkbox. This will create an array for our checkbox values. Now, let's add a couple more checkboxes. After the current checkbox line in form.html, add these lines:
Check me or not: <INPUT type="checkbox" name="mycheckbox[]" value="2"><BR> Check me or not: <INPUT type="checkbox" name="mycheckbox[]" value="3"><BR> |
In form.php we will now need to determine which checkboxes have been checked. Luckily for us, PHP gives us an easy way to loop through all the values in an array - a foreach loop. Continuing along in our form.php script, add these lines after the last ones we added:
foreach($_POST['mycheckbox'] as $value) { echo "<BR>You clicked checkbox number " . $value , "\n"; } |
If you type asdasd in the textbox and check checkboxes number 1 and 3, your output should look like:Great! You clicked the button!You typed asdasd in the textbox.You checked the checkbox.You clicked checkbox number 1You clicked checkbox number 3In form.html, you could very easily change the values of the checkboxes to anything you like. If you changed the value of checkbox 3 to dog, your output would look like:Great! You clicked the button!You typed asdasd in the textbox.You checked the checkbox.You clicked checkbox number 1You clicked checkbox number dogThat really doesn't make sense, but it shows you how the data is stored. The value that we are printing out isn't necessarily a numeric value. It is whatever value we assign that checkbox.
Next: Radio Buttons >>
More Miscellaneous Articles
More By Matt Wade
|
| · | | | · | | | · | | | · | | | · | | | · | | | · | | | · | | | · | | | · | | | · | | | · | | | · | | | · | | | · | | | · | | | | |
|