Skip to content Skip to sidebar Skip to footer

Keep Checkbox Checked After Form Submit

I have a page where I am displaying sql results as a table. I have it so that all the options are checked on default. However, when the user unchecks some locations and submits the

Solution 1:

Rather than hard-coding your "checked" attribute into each of your <input type="checkbox"> fields, you should be using PHP to determine if the GET variable associated with each field was passed to the script. In that case, you want to append the checked attribute to your <input> field. You can accomplish this by using a ternary operator right inside the field, as such:

<inputtype='checkbox'name='cities[]'value='CHI'<?= (in_array('CHI', $places)) ? 'checked' : ''; ?> >CHICAGO
<inputtype='checkbox'name='cities[]'value='DET'<?= (in_array('DET', $places)) ? 'checked' : ''; ?> >DETROIT
<inputtype='checkbox'name='cities[]'value='LA'<?= (in_array('LA', $places)) ? 'checked' : ''; ?> >LAS ANGELES
<inputtype='checkbox'name='cities[]'value='NYC'<?= (in_array('NYC', $places)) ? 'checked' : ''; ?> >NEW YORK
<inputtype='checkbox'name='cities[]'value='DALLAS'<?= (in_array('DALLAS', $places)) ? 'checked' : ''; ?> >DALLAS
<inputtype='checkbox'name='cities[]'value='SPR'<?= (in_array('SPR', $places)) ? 'checked' : ''; ?> >SPRINGFIELD
<inputtype='checkbox'name='cities[]'value='PHI'<?= (in_array('PHI', $places)) ? 'checked' : ''; ?> >PHILIDELPHIA

Solution 2:

you could send the parameter which checkbox is checked in GET request, and check it in your page e.g

if ($_GET['param1']==1) // checked
{
?>
<input type='checkbox' name='cities[]' value='CHI' checked>CHICAGO
<?else?>
<input type='checkbox' name='cities[]' value='CHI' >CHICAGO
?>

Solution 3:

<?php$citiesGroup = array();
$citiesGroup['CHI'] = 'CHICAGO';
$citiesGroup['DET'] = 'DETROIT';
$citiesGroup['LA'] = 'LAS ANGELES';
$citiesGroup['NYC'] = 'NEW YORK';
$citiesGroup['DALLAS'] = 'DALLAS';
$citiesGroup['SPR'] = 'SPRINGFIELD';
$citiesGroup['PHI'] = 'PHILIDELPHIA';

$citiesChecked = array();
if (!empty($_GET['cities'])) {
    foreach ($_GET['cities'] as$cityCode) {
        $citiesChecked[] = $cityCode;       
    }
}
else {
    foreach ($citiesGroupas$key => $value) {
        $citiesChecked[] = $cityCode;       
    }
}
?><?phpforeach ($citiesGroupas$cityId => $cityName) {
    $chekced = in_array($cityId, $citiesChecked) ? 'checked="checked"' : '';
?><inputtype='checkbox'name='cities[]'value='<?phpecho$cityId;?>'<?phpecho$chekced;?>><?phpecho$cityName;?><?php
}
?>

Get all checkboxed HTML in array and loop over it.

Above is the working code.

Post a Comment for "Keep Checkbox Checked After Form Submit"