Reputation: 823
I have this simple checkbox.
My problem is, if I select any of the checkbox, it should remain checked after form submission.
<input type="checkbox" name="services" value="make-up"> Make-up <br>
<input type="checkbox" name="services" value="massage"> massage <br>
<input type="checkbox" name="services" value="haircut"> Haircut <br>
I tried this code from radio button hoping to work but I failed.
<?php if (isset($services) && $services=="make-up") echo "checked";?>
I learned that it will work using localstorage.. however all the example I saw is very complicated.
Is there a simple way to solve this?
Thanks.
Upvotes: 1
Views: 386
Reputation: 12085
you can't access services as $services
you should access from REQUEST
like this $_REQUEST['services']
and assign to variable like this $services=$_REQUEST['services'];
HTML :
<input type="checkbox" name="services" value="make-up" <?php if(isset($services) && $services=="make-up"){ echo "checked"; } ?> > Make-up <br>
<input type="checkbox" name="services" value="massage" <?php if(isset($services) && $services=="massage"){ echo "checked"; } ?> > massage <br>
<input type="checkbox" name="services" value="haircut" <?php if(isset($services) && $services=="haircut"){ echo "checked"; } ?> > Haircut <br>
Upvotes: 0
Reputation: 1773
You can make it checked by:
<input type="checkbox" name="services[]" value="make-up"
<?php if (isset($_REQUEST['services']) && in_array("make-up",$_REQUEST['services'])) echo "checked";?>> Make-up <br>
Same for the other fields .
This will make it checked if posted value is same as that of checkbox value.
Upvotes: 1
Reputation: 12505
Since you are wanting to use a checkbox, you may want to array the input name(s):
<input type="checkbox" name="services[]" value="make-up"> Make-up <br>
<input type="checkbox" name="services[]" value="massage"> massage <br>
<input type="checkbox" name="services[]" value="haircut"> Haircut <br>
combined with a function like:
<?php
function isChecked($value)
{
return (!empty($_REQUEST['services']) && in_array($value,$_REQUEST['services']));
}
To end up with something like:
<input type="checkbox" name="services[]" value="make-up"<?php if(isChecked('make-up')) echo ' checked' ?>> Make-up <br>
<input type="checkbox" name="services[]" value="massage"<?php if(isChecked('massage')) echo ' checked' ?>> massage <br>
<input type="checkbox" name="services[]" value="haircut"<?php if(isChecked('haircut')) echo ' checked' ?>> Haircut <br>
Upvotes: 1