Page 1 of 1

Keep checkbox checked (or) unchecked

Posted: 11 Sep 2017, 10:49
by JanMolendijk
I`m using XAMP server + your script Update - Delete Data Using PHP

I have a checkbox but it does not stay checked
or unchecked after refreshing the page

this is my code for the checkbox

Code: Select all

<input  id="dating" 
        class="switch"
        type="checkbox" 
        value="1"
        name="dating"
        <?php echo $dating== "1" ? " checked" : ""; ?> >
<label for="switch"></label>

Keep checkbox checked (or) unchecked

Posted: 11 Sep 2017, 15:04
by Admin
Try this:

Code: Select all

<input id='dating' class='switch' type='checkbox' name='dating' value='1' <?php echo (isset($_REQUEST['dating']))? "checked='checked'":'';?> />
- The checkbox remains checked or unchecked after submiting the form (indicated via POST method), but if the page is opened again without submit, the checkbox will be unchecked because there is no form data.

Keep checkbox checked (or) unchecked

Posted: 11 Sep 2017, 15:43
by JanMolendijk
Dear admin thanks for supporting

But.. Is their another possibility what works 100% when i open the page again

Else the members have to check every time the checkbox.
Or do you have a better idea to do it ?

Keep checkbox checked (or) unchecked

Posted: 11 Sep 2017, 18:25
by Admin
You can put in session the status of that checkbox when form is submited, then use it from session.

Code: Select all

<?php
if(isset($_REQUEST['a_form_field'])){
  $_SESSION['cbx_dating'] = isset($_REQUEST['dating'])? "checked='checked'":'';
}
?>
<input id='dating' class='switch' type='checkbox' name='dating' value='1' <?php echo isset($_SESSION['cbx_dating'])? $_SESSION['cbx_dating']:'';?> />
- 'a_form_field' is the name of anoher field in that form.

With starting session at the beginning of your script:

Code: Select all

if(!isset($_SESSION)) session_start();