mercredi 1 juillet 2020

Not able to fetch correct values against checkboxes

I have a form that has a value of name and age against each checkbox as shown in the image.

enter image description here

The issue is that even when a checkbox is not selected but the input values against that checkbox is filled then it goes to the backend. I want that if the checkbox is not selected then even if the input text is filled the values of name and age against it should not go to the backend The value of age and name should only go to the backend if the checkbox is selected

<form method="POST" action="savedata.php">
    <tr>
        <td>
            <input name="checkbox_value[]" type="checkbox" data-id="<?php echo $id; ?>" >
        </td>
        <td>
            <input type="text" name="child_name[]" placeholder="Name" data-id="<?php echo $id; ?>" value="<?php echo $child_name; ?>">
        </td>
        <td>
            <input type="text" id="age" name="child_age[]" class="child-age" placeholder="Age" data-id="<?php echo $id; ?>" value="<?php echo $child_age; ?>">
        </td>
    </tr>
</form>

When fetching the data at savedata.php using

print_r($_POST);

I get the following array

Array
(
    [checkbox_value] => Array
        (
            [0] => on
            [1] => on
        )
    [child_name] => Array
        (
            [0] => child 1
            [1] => child 2
            [2] => child 3
        )
    [child_age] => Array
        (
            [0] => 4
            [1] => 6
            [2] => 10
        )
)

The resulting array that I want is

Array
(
    [checkbox_value] => Array
        (
            [0] => on
            [1] => on
        )
    [child_name] => Array
        (
            [0] => child 1
            [1] => child 2
        )
    [child_age] => Array
        (
            [0] => 4
            [1] => 6
        )
)

Would appreciate if anyone can tell how to solve this issue and also if this is not possible then is it possible to put a check that if the checkbox_value has 2 values then i can select 2 values from child_name and child_age array




Aucun commentaire:

Enregistrer un commentaire