Remember checkbox with localstorage onclick

2019-02-18 12:55发布

问题:

I am trying to create an options page for a Chrome extension. The first part sets the value in to local storage. Check for true and uncheck for false. The second part is supposed to update the check box if the user comes back at some other time and the settings will apply to the check box.

My problem is that the check box is never check when the user refreshes or closes the window and comes back, but the local storage will change to true or false. How do I make it so that the user can check the box and it will stay when the user returns at a later time or refresh esthe page.

    setStatus = document.getElementById('stat');
    setStatus.onclick = function() {
        if(document.getElementById('stat').checked) {
            localStorage.setItem('stat', "true");
        } else {
            localStorage.setItem('stat', "false");
        }
    }


getStstus = localStorage.getItem('stat');
    if (getStstus == "true") {
        console.log("its checked");
        document.getElementById("stat").checked;
    } else {
        console.log("its not checked");
    }

回答1:

Changing:

document.getElementById("stat").checked;

To:

document.getElementById("stat").setAttribute('checked','checked');

Would fix this. Since when adding .checked, that actually just checks if the checkbox is check.

You can also just do:

document.getElementById("stat").checked=true;   

Which does the same thing.


Please note that you need to change the second document.getElementById("stat").checked.

getStstus = localStorage.getItem('stat');
    if (getStstus == "true") {
        console.log("its checked");
        document.getElementById("stat").setAttribute('checked','checked');
    } else {
        console.log("its not checked");
    }​

JsFiddle Example



回答2:

You need to actually set the checked attribute to true in JavaScript.

Use:

document.getElementById("stat").checked = true;

Instead of:

document.getElementById("stat").checked;

Try it!



回答3:

I'm assuming you're saying that your storage is working, but you need to check the box using Javascript. In that case, use:

document.getElementById("stat").checked=true;

instead of

document.getElementById("stat").checked;

Reference: http://www.w3schools.com/jsref/prop_checkbox_checked.asp