Checkbox Php : Keep checked only the checked checkbox after submitting Get form

1k views Asked by At

This is my code

<?php foreach ($categories as $cat) {  ?>
    <li>
    <input id="category" name="category[]"  type="checkbox" value="<?= $cat->term_id; ?>" 
    <?php if (isset($_GET['category'])) echo "checked='checked'"; ?>><?= $cat->name ?></input>
    </li>
<?php } ?>

enter image description here

But when i submit the form the check boxes are all checked and what i wan't is to keep checked only the checkbox i checked not the others Example Below

enter image description here

2

There are 2 answers

1
Rajdeep Paul On BEST ANSWER

The problem is because of this line,

<?php if (isset($_GET['category'])) echo "checked='checked'"; ?>> ...
         ^^^^^^^^^^^^^^^^^^^^^^^^^^

Upon form submission $_GET['category'] will be set, hence this condition isset($_GET['category']) will hold true for all the checkboxes. And that's why all the checkboxes are checked irrespective of which one you checked earlier. So your foreach loop should be like this:

<?php foreach ($categories as $cat) {  ?>
    <li>
    <input id="category" name="category[]"  type="checkbox" value="<?= $cat->term_id; ?>" 
    <?php if (isset($_GET['category']) && in_array($cat->term_id, $_GET['category'])) { echo "checked='checked'"; } ?>><?= $cat->name ?></input>
    </li>
<?php } ?>
0
dheeraj Kumar On

please take a look on this code , i think it solved your issue.

<input type="checkbox" name="small" class="checkbox" <?=(isset($_POST['small'])?' checked':'')?> /> Small
<input type="checkbox" name="medium"  class="checkbox" <?=(isset($_POST['medium'])?' checked':'')?> >  Medium<br>