Quantcast
Channel: Fotan Web & Graphic Design » code
Viewing all articles
Browse latest Browse all 2

Forms with Multiple Checkbox Arrays

$
0
0

When I’m making web forms I can never remember exactly how to set “stuff” up.  I’m thinking I’m probably not the only one with this leaky brain problem.  Anyway, I was setting up a pretty large form today and had to create a group of check boxes.  When you’re doing a checkbox group and actually need to be able to see all of the checkboxes that were checked so you can save the info to a database, you have to jump through a couple hoops. First of all, here’s what you get when you do a search for “checkbox group html” in Google.

<input type="checkbox" name="checkbox_group" value="value1" />Value 1
<input type="checkbox" name="checkbox_group" value="value2" />Value 2
<input type="checkbox" name="checkbox_group" value="value3" />Value 3

That seems right, right?  Just name each checkbox in the group the same thing, and you’re good to go.  The problem is that when you try to read those values in PHP, all you get is the last one (value3, in this case). To get all three values, you need to make the checkboxes part of an array, like this.

<input type="checkbox" name="checkbox_group[]" value="value1" />Value 1
<input type="checkbox" name="checkbox_group[]" value="value2" />Value 2
<input type="checkbox" name="checkbox_group[]" value="value3" />Value 3

Then, when you need to get the values, you just step through the array, like any other array.

<?php
    if (isset($_POST['checkbox_group'])) {
        foreach($_POST['checkbox_group'] as $value) {
            // Do whatever you want with the value
            echo $value ."<br />";
        }
    }
?>

Pretty simple.  Just thought I would share so maybe it helps someone else.    

The post Forms with Multiple Checkbox Arrays appeared first on Fotan Web & Graphic Design.


Viewing all articles
Browse latest Browse all 2

Latest Images

Trending Articles



Latest Images