1

I'm trying to design a site (possibly to make into a Chrome extension) that will allow me to mark which characters have done which events in an online game I play. I'd love it if I had the option to save the values of the checkboxes between visits (and ideally, character names as well), but I'm not great at coding. Also, I'd strongly prefer it if this information could be saved/cleared/reloaded on command, and not otherwise.

The page in question, please pardon me if my code isn't efficient or attractive. I actually prefer to work with it a bit more bunched up, but I tidied it for your benefits.

There had been a suggestion here that I was trying to work with:

var i, checkboxes = document.querySelectorAll('input[type=checkbox]');

function save() {
    for (i = 0; i < checkboxes.length; i++) {
        localStorage.setItem(checkboxes[i].value, checkboxes[i].checked); 
    }
}

function load_() {
    for (i = 0; i < checkboxes.length; i++) {
        checkboxes[i].checked = localStorage.getItem(checkboxes[i].value) === 'true' ? true:false;
    }
} 

But while it works fine in the test, it won't work when I put it into my document (you'll see the var i at the top still, the rest of the code I'd put above the reset function).

Help?

3
  • try removing the quotes from the 'true' Commented Jun 19, 2013 at 8:14
  • 1
    Try to localize i: for (var i = 0; i < checkboxes.length; i++) {. Commented Jun 19, 2013 at 8:17
  • @MohammadAreebSiddiqui localStorage can only handle strings so it's correct the way he do now in that regard (but unnessesary check at the end: checkboxes[i].checked = (localStorage.getItem(checkboxes[i].value) === 'true'); would do). Commented Jun 19, 2013 at 8:23

1 Answer 1

1

This line:

var i, checkboxes = document.querySelectorAll('input[type=checkbox]');

is in the head of your document and runs immediately. None of the checkboxes exist at the time that it runs.

I'd suggest putting that script at the end of your body element or placing it in a window.onload = function() {}.

If you inspect the DOM structure in the working jsFiddle link you posted, you'll see it places the script at the end of the body element.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.