I’m trying to save and restore the state of a checkbox and other elements using localStorage when a user duplicates or closes the tab. It works well when I have just the checkbox, but as soon as I introduce additional elements, the checkbox state is not saved correctly in Chrome and Edge. Inspired by a similar issue discussed here, I created a version demonstrating the problem:
function save() {
var checkbox = document.getElementById('checkbox1zaal1');
var textarea = document.querySelector('textarea');
localStorage.setItem('checkbox1zaal1', checkbox.checked);
localStorage.setItem('box', textarea.value);
}
function load() {
var checked = JSON.parse(localStorage.getItem('checkbox1zaal1'));
document.getElementById("checkbox1zaal1").checked = checked;
document.querySelector('textarea').value = JSON.parse(localStorage.getItem('box'));
}
function wis() {
location.reload();
localStorage.clear();
}
load();
What am I missing? Is this a known bug in Chrome and Edge, or is there another approach I can try to ensure that the checkbox state is saved correctly alongside the other elements?
You have two (well, three at least) options:
Fix the retrieve: var checked = (localStorage.getItem('checkbox1zaal1') == "true")
Fix the save: localStorage.setItem('checkbox1zaal1', JSON.stringify({"checkbox" : checkbox.checked});
which will then require the set to be document.getElementById("checkbox1zaal1").checked = checked.checkbox;
Save multiple items in a single value, and retrieve an object (probably the better option…)
localStorage.setItem('formDetails', JSON.stringify({"checkbox1zaal1": checkbox.checked, "box": textarea.value}));
...
var data = JSON.parse(localStorage.getItem('formDetails'));
document.getElementById("checkbox1zaal1").checked = data.checkbox1zaal1;
document.querySelector('textarea').value = data.box;
I’m afraid it doesn’t. Steps to reproduce the issue: Navigate to the demo page/Codepen. Just check the checkbox. Click the save button, and then duplicate the tab. The checkbox on the duplicate tab is not checked.
the codepen shell will be boxing off localstorage, is why duplicating doesnt work (It assumes you want a clean slate every time it loads the code, because that’s what sandboxing usually wants!) - thats why i put a reload button onto the form, to demonstrate what it would do in a normal page.
Type something in the box; check the checkbox.
Click save. This writes to localStorage.
Change the text in the box. Uncheck the checkbox.
Click reload. This pulls the state from localStorage and restores the form.
Only difference is i’m calling load() on a button push, in addition to page creation.