How to set checkbox checked based on a variable
I've done my best to search all of the answers and can't find anything that answers this specifically. So, if you find something, please let me know and I'll remove this right away.
I created a JSFiddle to show my problem (JS portion copied below for ease of reference): http://jsfiddle.net/hg67R/1/
When I am trying to set the value of a checkbox based on the value of a variable it will not seem to set correctly. The example I created should save the current state of each checkbox (which is does correctly). Then, no matter how you change those checkboxes, it should change them back when you click load. The storage variables are correct but it is not setting the checkboxes correctly. I'm certain it is something obvious but I sure can't see it.
function save() {
localStorage.setItem("numbers", document.getElementById("Numbers").checked);
localStorage.setItem("tips", document.getElementById("Tips").checked);
}
function load() {
document.getElementById("Numbers").checked = localStorage.numbers;
document.getElementById("Tips").checked = localStorage.tips;
console.log("numbers storage: " + localStorage.numbers);
console.log("numbers box: " + document.getElementById("Numbers").checked);
console.log("tips storage: " + localStorage.tips);
console.log("tips box: " + document.getElementById("Tips").checked);
}
The console.logs just show me that the variables are storing and loading correctly.
Thanks!
in addition to mrk his answer
http://jsfiddle.net/Icepickle/NVw3L/
where the biggest change is that i check if the localStorage value exactly agrees with "true"
document.getElementById("Numbers").checked = localStorage.numbers === 'true';
Two things:
Localstorage stores string keys and string values
The proper value of a checkbox's checked attribute is clearly described here:
What's the proper value for a checked attribute of an HTML checkbox?
Specifically, this part:
A switch is "on" when the control element's checked attribute is set.
What this means is that it doesn't matter what one puts there, and in fact it only needs to be defined. All of the following will be checked:
<input name="checkbox_name" id="checkbox_id" type="checkbox" checked>
<input name="checkbox_name" id="checkbox_id" type="checkbox" checked="yes">
<input name="checkbox_name" id="checkbox_id" type="checkbox" checked="no">
<input name="checkbox_name" id="checkbox_id" type="checkbox" checked="blue">
<input name="checkbox_name" id="checkbox_id" type="checkbox" checked="false">
And only the following will be unchecked:
<input name="checkbox_name" id="checkbox_id" type="checkbox">
链接地址: http://www.djcxy.com/p/56050.html
上一篇: 复选框在mvc3中不起作用
下一篇: 如何根据变量设置复选框