Home > OS >  Checkbox state isn't applied correctly from the localStorage
Checkbox state isn't applied correctly from the localStorage

Time:11-05

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"  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?

CodePudding user response:

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");
    }
});
  • Related