I'm using the following code for a series of check-boxes.
How can I change the code to prevent the checkboxes from emptying when user submits the form.
<?php
$services = array(
'Tree Felling',
'Height Reduction',
'Crown Thinning',
'Deadwooding/Ivy Removal',
'Stump Grinding',
'Other'
);
foreach ($services as $option) {
?>
<label><input id="<?= $option ?>" type="checkbox" name="services[]" <?php
if ($_POST['services'] == $option) {
echo 'CHECKED';
}
?> value="<?= $option ?>" /><?= $option ?></label>
<?
}
?>
I tried this - but It didn't work out. Am I on the right lines?
<?php
$services = array(
'Tree Felling',
'Height Reduction',
'Crown Thinning',
'Deadwooding/Ivy Removal',
'Stump Grinding',
'Other'
);
foreach ($services as $option) {
?>
<label><input id="<?= $option ?>" type="checkbox" name="services[]" value="<?= $option ?>" /><?= $option ?></label>
<?
}
?>
You need to check to see if $_POST['services'] is available via isset() (basically that the form's been submitted) and check to see if that service is in the array using in_array(). This worked for me:
<?php
$services = array(
'Tree Felling',
'Height Reduction',
'Crown Thinning',
'Deadwooding/Ivy Removal',
'Stump Grinding',
'Other'
);
foreach ($services as $option) {
?>
<label><input id="<?= $option ?>" type="checkbox" name="services[]" <?php
if ( isset($_POST['services']) and in_array($option, $_POST['services']) ) {
echo 'CHECKED';
}
?> value="<?= $option ?>" /><?= $option ?></label>
<?
}
?>
If the form submission is in the same page, you can get the value (if it's checked), and add it to the input
with an if
statement.
Otherwise, if you want that some of thouse checkboxes are checked, and other ones no, you can put an array inside, like:
$services = array(array("Name service 1", "checked"), array("Name service 2", "")); //leaving empty thouse you don't want checked.
Hope I helped you!