简体   繁体   中英

Keeping checkbox state after submit with status checked on first page load

I have this html form with checkboxes that keep their status checked or unchecked after submitting the form and reloading the page:

<form method="post" action="">
<input type="checkbox" name="keyword1" value="keyword1" <?php if(isset($_POST['keyword1'])) echo "checked='checked'"; ?> />keyword1
<input type="checkbox" name="keyword2" value="keyword2" <?php if(isset($_POST['keyword2'])) echo "checked='checked'"; ?> />keyword2
<input type="checkbox" name="keyword2" value="keyword3" <?php if(isset($_POST['keyword2'])) echo "checked='checked'"; ?> />keyword3
<input type="submit"  />
</form>

Problem is, that at first page load the checkboxes are unchecked. Is there any possibility to have all checkboxes with status checked at the beginning and then keep their new status after submit? So far I could not figure out how to do this. Any help would be much appreciated. Thanks,

you could use $_SESSION instead of $_POST :

<input type="checkbox" name="keyword1" value="keyword1" <?php if(isset($_SESSION['keyword1'])) echo "checked='checked'"; ?> />keyword1

And then put this on the top of your file :

session_start();
if (isset($_POST['my_form'])) {
    if (isset($_POST['keyword1'])) {
        $_SESSION['keyword1'] = 'checked';
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM