Retaining checkbox value of a form after posting

Keep a checkbox selected after validation

For a sticky form, derive the checked attribute from submitted data instead of assuming the field will always be present.

$agreed = isset($_POST['agreed']);
$checked = $agreed ? ' checked' : '';

echo '<input type="checkbox" name="agreed" value="yes"' . $checked . '>';
This is first checkbox
This is second checkbox

Use the checkbox?> Use the checkbox in above form and on submit the status of the Checkboxes are retained.

This tutorial is part of the series where we will try to understand how to retain value of every component of a form. You can read our main tutorial on how to retain value for component of a form here.

For a simple sticky form, keep the form and validation on the same page and redisplay the submitted state directly. A redirect is useful for Post/Redirect/Get after a successful action, but ordinary checkbox values do not need to be copied into the URL.

We will use the example of two checkbox but same system can be extended to more than two or single checkbox in a form.

Here is a same-page example. Because unchecked checkboxes are omitted from the request, use isset() instead of assuming the key exists.

Related: JavaScript checkbox handling and HTML forms.

$t1 = isset($_POST['t1']);
$t2 = isset($_POST['t2']);

$t1v = $t1 ? 'checked' : '';
$t2v = $t2 ? 'checked' : '';

echo "<form method='post' action=''>
<input type='checkbox' name='t1' value='yes' $t1v> First
<input type='checkbox' name='t2' value='yes' $t2v> Second
<input type='submit' value='Submit'>
</form>";
Difference between GET and POST method of Form submission
PHP Form Managing Radio button using PHP



Subscribe to our YouTube Channel here



plus2net.com







AARON

04-01-2019

I have been searching the whole net for this and here I am with the true answer to my problem. Thank you!




PHP video Tutorials
✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer