Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
545 views
in Technique[技术] by (71.8m points)

javascript - localStorage how to save a checkbox

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 the checkbox and i press the save button it doesn't save the checkbox.

how can i achieve this?

this is my code:

<script>
function save(){
    var checkbox = document.getElementById('checkbox1zaal1');
    if(document.getElementById('checkbox1zaal1').checked) {
        localStorage.setItem('checkbox1zaal1', true);
    }
}

function load(){    
    var checked = localStorage.getItem('checkbox1zaal1');
    if (checked == true) {
        document.getElementById("checkbox1zaal1").setAttribute('checked','checked');
    }
}
function wis(){
    location.reload();
    localStorage.clear()

}
</script>

<body onload="load()">
<input type="button" id="ReserveerButton1" value="save" onclick="save()"/>
<input type="button" id="Wisbutton1" value="delete" onclick="wis()"/>
<input type="checkbox" id="checkbox1zaal1">1e film van de dag</input>
</body>

thanks for any advice!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);
}

Demo: http://jsfiddle.net/Lwxoeyyp/1/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...