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();
<input type="button" id="ReserveerButton1" value="save" onclick="save()" />
<input type="button" id="Wisbutton1" value="delete" onclick="wis()" />
<input type="checkbox" id="checkbox1zaal1">
<textarea>Hello, world!</textarea>
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?
2
Answers
ADD :
I followed the steps you provided to reproduce the problem, but it did not reproduce it. But when I turned off the "Allow sites to save and read cookie data (recommended)" setting, I could reproduce the problem. So please enter "edge://settings/content/cookies" in the Edge address bar and check if this setting is turned off to cause this problem.