I want to save a checkbox with localstorage. So that when i have checked the box and I close the browser and i re-open it, it will still be checked. right now if i click on
1). Because boolean true
is not equal to string "true"
. So comparison checked == true
is always false
, and checkbox never gets checked.
Instead try this:
var checked = JSON.parse(localStorage.getItem('checkbox1zaal1'));
if (checked == true) {
document.getElementById("checkbox1zaal1").checked = true;
}
And remember whatever you store in localStorage is always a string, and only a string. That's why when you save something more complex then primitive value (for example some object) make sure to use JSON.stringify
on it first.
When you retrieve the value from localStorage you should convert it back to it's corresponding javascript type.
In general load
function can also be improved:
function load(){
var checked = JSON.parse(localStorage.getItem('checkbox1zaal1'));
document.getElementById("checkbox1zaal1").checked = checked;
}
2). Another problem will come up once you try to uncheck checkbox. You are not handling it currently, so change save
function to this one:
function save(){
var checkbox = document.getElementById('checkbox1zaal1');
localStorage.setItem('checkbox1zaal1', checkbox.checked);
}