Reputation: 488
So what I want to do is the following:
1
if box is checked, or 0
if box is unchecked1
or a 0
in plain text, having fetched the aforementioned value from localstorage.Here is my code, but it is not working (when page is reloaded, box is not checked; and null
is returned instead of a 1
or a 0
):
script.js
// here is to set item in localstorage when you click the check box.
vvvvvvv = document.getElementById('xxxx');
vvvvvvv.onclick = function() {
if(document.getElementById('xxxx').checked=true) {
localStorage.setItem('yyyyyyy', "1");
} else {
localStorage.setItem('yyyyyyy', "0");
}
}
// here is to fetch the item stored in local storage, and use that value
// to check or uncheck the box based on localstorage value.
zzzzzzz = localStorage.getItem('yyyyyyy');
if (zzzzzzz === null) {
localStorage.setItem('yyyyyyy', "0");
document.getElementById("xxxx").checked=false;
}
else {
if (zzzzzzz === "1") {
document.getElementById("xxxx").checked=true;
} else if (zzzzzzz === "0") {
document.getElementById("xxxx").checked=false;
}
}
output.js
// here is to output the value to the web page so we can know
// what value is stored in localstorage.
wwwwwwww = localStorage.getItem('yyyyyyy');
document.write(wwwwwwww);
page.html
<!-- here is the check box for which the scripts above are based from -->
<input type="checkbox" id="xxxx">Do you like summer?
<br><br>
<!-- here is where it will display the value from localstorage -->
<script src="output.js">
Upvotes: 0
Views: 1456
Reputation: 28387
There are a couple of syntax errors in your code, which is why it is failing to store the value in localStorage. For example, here is one:
Equality operator in your onclick (== instead of =):
if(document.getElementById('xxxx').checked == true) {
or just:
if(document.getElementById('xxxx').checked) {
Another one:
Extra dangling {
before the else
as pointed out by dystroy.
Now it is working just fine:
See fiddle: http://jsfiddle.net/nng6L/6/
You did not fix the second! There was an extra {
dangling before the else
.
Upvotes: 0
Reputation: 26143
I removed some unnecessary bits of the script and tidied it a little and came up with this...
// here is to set item in localstorage when you click the check box.
vvvvvvv = document.getElementById('xxxx');
vvvvvvv.onclick = function() {
if(document.getElementById('xxxx').checked) {
localStorage.setItem('yyyyyyy', "1");
} else {
localStorage.setItem('yyyyyyy', "0");
}
}
// here is to fetch the item stored in local storage, and use that value
// to check or uncheck the box based on localstorage value.
zzzzzzz = localStorage.getItem('yyyyyyy');
console.log(zzzzzzz);
if (zzzzzzz === "1") {
document.getElementById("xxxx").checked=true;
} else {
document.getElementById("xxxx").checked=false;
}
Here's a working jsFiddle...
Check the checkbox and refresh the page to see it work.
Upvotes: 2