Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Checkbox state isn't applied correctly from the localStorage

I have a simple checkbox. I want to save the state that the user set (so if they checked the checkbox, it stays that way after the page reload, if they checked and unchecked it, it should stay unchecked after the page reload).

<input type="checkbox" class="dm-btn" id="dmtoggle" style="display:none;">
<label for="dmtoggle"></label>
$(".dm-btn").on("click", function(){
    localStorage.setItem("dm-checkbox", $(".dm-btn").prop('checked'));
});

$(document).ready(function() {
    let dmState = localStorage.getItem("dm-checkbox");
    $(".dm-btn").prop('checked', dmState);

    if (dmState == true){
        console.log("checked");
    } else {
        console.log("not checked");
    }
});

The problem is that when I check it and uncheck it will always be checked after the page reload. I have to clear cookies to uncheck it. How to fix that?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The issue is that local storage only stores strings, so your condition will always be false

To fix, either parse your storage item back to a boolean with JSON.parse, e.g.

let dmState = JSON.parse(localStorage.getItem("dm-checkbox"));

or else explicitly cast it to a boolean. e.g

let dmState = !!localStorage.getItem("dm-checkbox");

In both cases your condition would then just be…

if (dmState) {
...

That is you don’t need to check a boolean value against true or false – because it is true or false. e.g.

$(document).ready(function() {
    let dmState = !!localStorage.getItem("dm-checkbox");
    $(".dm-btn").prop('checked', dmState);
    if (dmState){
        console.log("checked");
    } else {
        console.log("not checked");
    }
});
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading