ossUter
ossUter

Reputation: 39

Get value from checkbox - 0 when unchecked, 1 when checked

I need to get value 1 - when checkbox is checked and 0, when it is unchecked.

    <input type="checkbox" name="data[color][]" class="color" value="1" checked>

Data array - stores other data that is retrieved from input type text and select. It's working fine. The problem occurs when I try to retrieve data from an input of type checkbox. Brief description of the "project": the script is to add several records to the database simultaneously. To start with, one section is available for data entry, for a single record - using JS after clicking the appropriate button - the next section appears and so on up to a certain maximum number of sections/possible records. In general, the script works correctly - records are added. The problem is with the color column that gets the data from the aforementioned checkbox. After the form is submitted - there is a reorganization of the board to somehow present this more reasonably. PHP code:

foreach($data as $columnName => $columnValues){
        foreach($columnValues as $rowIndex => $columnValue){
            $result[$rowIndex][$columnName] = $columnValue;
        }
}

To get at the value:

foreach($result as $r => $value){
    if(isset($value['color'])){
        $color = 1;
    } else {
        $color = 0;
    }
}

While with the number of records <= 2 it works correctly, when there are > 2 values are not assigned correctly. What am I doing wrong? If you need more information - please write. I seem to have pasted everything related to this.

When using var_dump for $value['color'] with 4 records there is this result:

string(1) "1"
string(1) "1"
NULL
NULL

Where only the first and fourth checkbox was checked.

Upvotes: 0

Views: 262

Answers (1)

AbraCadaver
AbraCadaver

Reputation: 78994

Unlike input type text and select, only checked checkbox inputs will be submitted. So using dynamic arrays [], if you have 3 and only the first is checked, then it will be submitted as $_POST['data']['color'][0]. If you only check the third one it will also be submitted as $_POST['data']['color'][0], etc... With the current code there is no way to track them.

Probably the best way to do this is to use a hidden input with the same name before the checkbox with value 0 as default, so that all checkboxes are submitted, either with 0 or 1. You need to specify the numerical indexes for each:

 <input type="hidden" name="data[color][0]" value="0">
 <input type="checkbox" name="data[color][0]" class="color" value="1" checked>

 <input type="hidden" name="data[color][1]" value="0">
 <input type="checkbox" name="data[color][1]" class="color" value="1" checked>

 <input type="hidden" name="data[color][2]" value="0">
 <input type="checkbox" name="data[color][2]" class="color" value="1" checked>

Now you'll always get 3 $_POST['data']['color'] elements, either 0 or 1.

Upvotes: 1

Related Questions