0

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 Answers 2

1

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 } ?>
Sign up to request clarification or add additional context in comments.

1 Comment

@Minimal Glad I could help. ;-) By the way, you should get into the habit of accepting answers, otherwise the questions will be floating around as open questions. Moreover, it'll also encourage other developers to help you further. Please read, how to accept answer on Stack Overflow?
0

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.