简体   繁体   中英

How to $_POST input text related to checkbox array with PHP?

I have checkboxes for days of week like below:

<input type="checkbox" name="day[]" id="monday" value="Monday">
<label for="monday">Monday</label>
<input name="day-detail[]" type="text" />

<input type="checkbox" name="day[]" id="tuesday" value="Tuesday">
<label for="tuesday">Tuesday</label>
<input name="day-detail[]" type="text" />

And so on.

Notice that there is related input text for each day.

I would like to know if is possible for me to print the input text field only if the checkbox is checked. I need to do this several times with many others checkboxes so I tryed with the following function:

<?php
function checkboxes($checkbox_field, $default = '') {
    if(isset($_POST[$checkbox_field]) and !empty($_POST[$checkbox_field])) {
        $post_field = $_POST[$checkbox_field];
        if (is_array($post_field)) {
            if(!empty($_POST[$checkbox_field.'-detail'])) {
                return join(', ', $post_field.': '.$_POST[$checkbox_field.'-detail']);
                echo $_POST[$checkbox_field.'-detail'];
            }
            else {
                return join(', ', $post_field);
                echo $_POST[$checkbox_field.'-detail'];
            }
        }
    } else {
        return $default;
    }
}

echo "The weekly sales are:  ".checkboxes('day');
?>

This is what I'm trying to print:

Monday: value from text input , Tuesday: value from text input "

The checked checkboxes are printed ok but the text inputs are not.

What could be wrong?

Thanks in advance.

I think what you need is to use an index to the fields. So let's say Tuesday is selected. Then $_POST["day"][1] gives you TRUE (the checkbox), and $_POST["day-detail"][1] gives you the corresponding text (ie the 1 is used as an index to both fields).

In practice the index will actually be a variable in a for loop, as I'm imagining you looping over all checkboxes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM