Solution 1 :

Only checked checkboxes will be submitted. You can keep the checkbox and textarea values paired by adding the same key to their name arrays. The device ID would probably work well for that.

    <input type="checkbox" name="devices[<?php echo $device["id"] ?>]" value="<?php echo $device["id"].$dev_comment ?>">
    <div class="input-group">
        <textarea name="dev_comment[<?php echo $device["id"] ?>]" placeholder="comment" rows="1" cols="50"><?php echo $dev_comment; ?></textarea>

If the device id is not unique, you can just use the index from the foreach loop.

Then in the form handler code you can use that shared id from the checkboxes to access the comments:

foreach ($_POST['devices'] as $id => $value) {
    // do something with $_POST['dev_comment'][$id]

Problem :

I have a table with some items on it and each row has a checkbox and a textarea. When I pres submit I want to take the values of the textareas ONLY for the respective checked checkbox and NOT for the ones that aren’t checked even if they have textareas with some content.

                <form method="post">
                <?php if (!empty($arr_devices)) { ?>
                    <?php foreach ($arr_devices as $device) : ?>
                                <input type="checkbox" name="devices[]" value="<?php echo $device["id"].$dev_comment ?>">
<div class="input-group">
                                    <textarea name="dev_comment[]" placeholder="comment" rows="1" cols="50"><?php echo $dev_comment; ?></textarea>

                    <?php endforeach; ?>
                <?php } ?>
                <input class="btn" type="submit" name="submit" value="Report">

Printed arrays after summitted:

  Device_id([0] => 790 [1] => 1140 [2] => 1142 ) 
  Comments( [0] => sdf [1] => sdfsdfs [2] => [3] => fsdfsd [4] => )

as it is now, I am able to receive ONLY the device_id for the checked ones but ALL the values(even empty ones) for the comments when I am submitting. Why is that happening and how to fix it?


Comment posted by vadivel a

Remove the empty value after submitted