samedi 1 septembre 2018

Prevent checkbox values from shifting after page reload on form submission

I have created a form which reloads in case of an error and goes to some other page in case of successful submission.

I don't want users to fill all values again and again in case of error so I store them in session variables and fill them back in the form.

Here is the HTML of the form:

<form action="preference.php" method="post">
<input id="optiona-cb" name="userpref[]" type="checkbox" value="optiona" <?php if((isset($_SESSION['userpref'][0]) && $_SESSION['userpref'][0])) { echo 'checked'; } ?>/>
<label for="optiona-cb">optiona</label>
<input id="optionb-cb" name="userpref[]" type="checkbox" value="optionb" <?php if((isset($_SESSION['userpref'][1]) && $_SESSION['userpref'][1])) { echo 'checked'; } ?>/>
<label for="optionb-cb">optionb</label>
<input id="optionc-cb" name="userpref[]" type="checkbox" value="optionc" <?php if((isset($_SESSION['userpref'][2]) && $_SESSION['userpref'][2])) { echo 'checked'; } ?>/>
<label for="optionc-cb">optionc</label>
... More Input Fields
</form>

Here is code from preference.php:

$_SESSION['userpref'] = $_POST['userpref'];
$_SESSION['user_login'] = $_POST['user_login'];
$_SESSION['user_email'] = $_POST['user_email'];
.. More code

On page reload, the username and email values are filled correctly. However, the checkbox values shift. For example, if a user only checks optionc, the value optiona gets checked on reload. Similarly, if a user checks optiona and optionc, the values optiona and optionb get checked.

In other words, "holes" in the ticked checkboxes get filled on page reload. How can I make sure that the checkbox values don't shift to fill empty values?

I am using WordPress if that matters. :)




Aucun commentaire:

Enregistrer un commentaire