Jump to content

Cookies and checkbox


Go to solution Solved by gizmola,

Recommended Posts

Hey there, im trying to create two stylesheets for my project, the first one is light and the second is dark, so basically i have this input checkbox type, so i want to display dark stylesheet if the button is checked and light if the button is unchecked

 

basically my function

<?php
if(!isset($_COOKIE['mode'])) {
	$mode = "light";
}

if (!empty($_POST['mode']) && $_POST['mode'] == "dark" ) {
	$mode = "dark";
	setcookie("mode", "dark");
}
else {
	$mode = "light";
	setcookie("mode", "light");
}
?>

and in my header

<?php
include 'inc/functions/cookies.php';
if($_COOKIE['mode'] == "dark") {
	echo "<link href='dark.css' rel='stylesheet' type='text/css' />";
}
if($_COOKIE['mode'] == "light") {
	echo "<link href='light.css' rel='stylesheet' type='text/css' />";
}
else {
	echo "<link href='light.css' rel='stylesheet' type='text/css' />"; 
}
?>

and the html input checkbox is

<input type="checkbox" onChange="this.form.submit()" value="<?=$mode;?>" name="mode" <?=$_COOKIE['mode'] == "dark" ? "checked" : "" ?> />

 

i might be overthinking this or something because i cannot figure it out, thanks in advance

Link to comment
https://forums.phpfreaks.com/topic/314259-cookies-and-checkbox/
Share on other sites

So what is the problem?  I would think that you would just include either the light css module or the dark one, depending upon the mode value.  Use $mode as the name of the css file perhaps.

You could also make that last line of code a lot easier to read/write:

echo "<input type='checkbox' onChange='this.form.submit()' value='$mode' name='mode' $mode_chk_flag/>";

Set the $mode_chk_flag when you set the $mode value.

AND - you don't really need the cookie unless you are trying to retain the setting between sessions.

Edited by ginerjm
9 hours ago, ginerjm said:

So what is the problem?  I would think that you would just include either the light css module or the dark one, depending upon the mode value.  Use $mode as the name of the css file perhaps.

You could also make that last line of code a lot easier to read/write:

echo "<input type='checkbox' onChange='this.form.submit()' value='$mode' name='mode' $mode_chk_flag/>";

Set the $mode_chk_flag when you set the $mode value.

AND - you don't really need the cookie unless you are trying to retain the setting between sessions.

the problem, that it doesn't work at all, lets say the box is checked (current dark), and i want to change it (uncheck to light) there is no possible way i know to check if the checkbox is being unchecked

i ended up doing this, so far checking to dark is working

<?php
if(!isset($_COOKIE['mode'])) {
	$mode_check_flag = NULL;
	$mode = NULL;
	setcookie("mode", "light");
}

if (isset($_COOKIE['mode'])) {
	$mode =  $_COOKIE['mode'];
	echo "Cookie: " . $_COOKIE['mode'] . "<br>";
	
}
if (isset($_COOKIE['mode']) && $_COOKIE['mode'] == "dark") {
	$mode_check_flag = "checked";
}
else {
	$mode_check_flag = NULL;
}

if (!empty($_POST['mode']) && $_POST['mode'] == "light" ) {
	$mode = "dark";
	$mode_check_flag = "checked";
	setcookie("mode", $mode);
}
if (!empty($_POST['mode']) && $_POST['mode'] == "dark" ) {
	$mode = "light";
	$mode_check_flag = NULL;
	setcookie("mode", $mode);
}

echo "Mode: " . $mode . "<br><br>";

?>

<html>
<head>
<title>Testing</title>
</head>
<body>
<form action="" method="post">
<input type="checkbox" onChange="this.form.submit()" value="<?=$mode;?>" name="mode" <?=$mode_check_flag; ?> /> Dark Mode<br><br>
</form>
</body>
</html>

 

but when i uncheck the checked it doesnt change to light which is the last if statement, anyone knows why?

3 minutes ago, gizmola said:

An unchecked checkbox isn't passed when a form is posted.  

You could correct for that, or you could use a more appropriate form element (radio button or select list).

isn't there any possible way to do it with checkbox type? or a tweak with jquery?

  • Solution

Yes, although again the UI is incorrect.  Checkboxes are not mutually exclusive.  So you are just doing this UI in the wrong way.  Your form code is also wrong. 

  • You have a label that is hardwired to dark, yet you have variables toggling the value from light to dark. 
  • When a form is rendered, it should always be checked, because you are using the checkbox to toggle from light to dark.  

This means that a value for the checkbox will never be set in the way you using this.  A newly rendered form will always have a value (light or dark) and will be checked.  Once you uncheck it, you'll submit the form, and the checkbox will not be passed.

However, to your question, you have 2 choices:

  • Write a little js that checks the check/uncheck state and sets a hidden element, which you use on submit
  • Just have php check for isset() or use array_key_exists.  If ! isset() then it was unchecked.  You want to check the request method to make sure the form was actually posted.

Not that I'd advise this, but in this case, and again you have to be logical and clear, if the form is submitted, then you are looking to toggle the value.  

<php

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $mode = empty($_COOKIE['mode']) ? 'Light' : $_COOKIE['mode'];
    //Toggle it
    $mode = ($mode == 'Light') ? 'Dark' : 'Light';
    setCookie('mode', $mode);
} else {
    $mode = empty($_COOKIE['mode']) ? 'Light' : $_COOKIE['mode'];
    setCookie('mode', $mode);   
}

// Now can use $mode to render
?>

<input type="checkbox" onChange="this.form.submit()" value="<?= $mode ?>" name="mode" checked>
<label for="mode"><?php echo "$mode Mode"; ?><label><br>

 

Again when you think about it, the actual value of the checkbox is irrelevant as you are really going to toggle the cookie value on any submit.

     

    The other option is to use some js.  Probably what I would do is use a hidden field, so that you could rely on the submission, but then when you have a cookie you are also relying on, this whole scheme makes less sense

     

    Something like this could work:

    <?php
    if ($_SERVER['REQUEST_METHOD'] == 'POST') {
        $mode = empty($_COOKIE['mode']) ? 'Light' : $_COOKIE['mode'];
        //Toggle it
        $mode = ($mode == 'Light') ? 'Dark' : 'Light';
        setCookie('mode', $mode);
    } else {
        $mode = empty($_COOKIE['mode']) ? 'Light' : $_COOKIE['mode'];
        setCookie('mode', $mode);   
    }
    ?>
    <!DOCTYPE html>
    <html lang="en">
        <head>
            <title>Form Test</title>
            <script type="text/javascript">
                function toggleMode() {
                    let cb = document.getElementById("cbmode");
                    let newMode = document.getElementById("new_mode");
                    newMode.value = (cb.value == "Light") ? "Dark" : "Light";
                    console.log(newMode.value);
                    document.getElementById("modeForm").submit();
                }
            </script>
        </head>
        <body>
            <form id="modeForm" method="post">
                <input type="checkbox" onChange="toggleMode()" value="<?= $mode ?>" id="cbmode" name="cbmode" checked>
                <label for="cbmode"><?php echo "$mode mode"; ?></label>
                <input id="new_mode" type="hidden" value="<?= $mode ?>">
            </form>
        </body>
    </html>

     

     

    This thread is more than a year old. Please don't revive it unless you have something important to add.

    Join the conversation

    You can post now and register later. If you have an account, sign in now to post with your account.

    Guest
    Reply to this topic...

    ×   Pasted as rich text.   Restore formatting

      Only 75 emoji are allowed.

    ×   Your link has been automatically embedded.   Display as a link instead

    ×   Your previous content has been restored.   Clear editor

    ×   You cannot paste images directly. Upload or insert images from URL.

    ×
    ×
    • Create New...

    Important Information

    We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.