Reputation: 11
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 } ?>
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
Upvotes: 0
Views: 1107
Reputation: 16963
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 } ?>
Upvotes: 1
Reputation: 372
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>
Upvotes: 0