Gil
Gil

Reputation: 43

maintain checkbox which were checked after submit

I know there's "PHP keep checkbox checked after submitting form" on here, but that thread does not solve my problem, because I have multiple checkbox, what I need is when you check a checkbox, this stay checked after submit.

At the moment with this code nothing happens, I tried another way but when I check "id7" checkbox, all the checkbox get checked.

I have to know which checkbox was checked by the id that I give it, but I do not know how.

while ($fila = mysql_fetch_array($rs)) {
    echo utf8_encode("
            <tr>
              <td>
                ".$fila['title']."
              </td>
              ");?>
              <td>
                <input type="checkbox" name="checklist[]" value="<?php echo htmlspecialchars($fila['id']); ?>" <?php if(isset($_POST['checklist[]']) && is_array($_POST['checklist[]']) && in_array('$fila', $_POST['checklist[]'])) echo 'checked="checked"'; ?> />
              </td>
              <?php 
            }
          }
       ?>

Upvotes: 0

Views: 1532

Answers (2)

Chay Harley
Chay Harley

Reputation: 1

"name" is like a variable name - by using checklist[] you're defining an array as the variable. Why not just name each checkbox properly? When the form is submitted, use the contents of $_POST to set each variable into the user's $_SESSION.

If the page is refreshed, use the values from $_SESSION to determine if the checkbox should be ticked. Something like (untested):

 <input type="checkbox" name="vehicle" value="Bike" 
<?php if (isset($_SESSION['bike_checked']) echo 'checked'; ?>> I have a bike<br>
 <input type="checkbox" name="vehicle" value="Car" 
<?php if (isset($_SESSION['car_checked']) echo 'checked'; ?>> I have a car<br>
 <input type="submit" value="Submit">

Upvotes: 0

David Fang
David Fang

Reputation: 1787

First, the value of checkbox is $fila['id'] so when you are checking, use $fila['id'] instead of $fila. Also, when PHP receive array input fields with [] in their names the [] will be removed so that the correct POST variable is $_POST['checklist'].

Try changing this line:

<input type="checkbox" name="checklist[]" value="<?php echo htmlspecialchars($fila['id']); ?>" <?php if(isset($_POST['checklist[]']) && is_array($_POST['checklist[]']) && in_array('$fila', $_POST['checklist[]'])) echo 'checked="checked"'; ?> />

to

<input type="checkbox" name="checklist[]" value="<?php echo htmlspecialchars($fila['id']); ?>" <?php if(isset($_POST['checklist']) && is_array($_POST['checklist']) && in_array($fila['id'], $_POST['checklist'])) echo 'checked="checked"'; ?> />

Upvotes: 1

Related Questions