We may want to put some checkboxes on the options page, like this:
<html> <head><title>Extension Options</title> <script type="text/javascript"> // Saves options to localStorage. function saveOptions() { localStorage["tstChkbox"] = document.getElementById("chkbx").checked; } // Restores value from localStorage. function restoreOptions() { var value = localStorage["tstChkbox"]; if (null != value) document.getElementById("chkbx").checked = value; } </script> </head> <body onload="restoreOptions()"> <form> <input type="checkbox" id="chkbx" /> Check Box <br /> </form> <button onclick="saveOptions()">Save</button> </body> </html>
But this piece of code doesn't work. If you step through it in the debugging tool, it looks perfect. But the checkbox is always checked every time the options page is loaded even if you uncheck it before save. Why?
When you uncheck the checkbox, it seems the following statement have saved the Boolean false to the localStorage. But it actually saves a "false" string.
localStorage["tstChkbox"] = document.getElementById("chkbx").checked;
So when we retrieve it from the localStorage, we retrieve a "false" string. In JavaScript, any string -- including "false" -- will be converted to Boolean true when the type conversion is needed. So the following piece of code will always check the checkbox when the "false" string is retrieved from localStorage.
var value = localStorage["tstChkbox"]; if (null != value) document.getElementById("chkbx").checked = value;
This is not what we want. To fix it, we can do a little conversion for the value retrieved from localStorage:
function toBool(str) { if ("false" === str) return false; else return str; }
Then we can set the value for checkbox like this:
var value = localStorage["tstChkbox"]; if (null != value) document.getElementById("chkbx").checked = toBool(value);
6 comments:
thanks for the tip. Unfortunately it produces the opposite problem, where the checkbox ends up always being unchecked instead of checked.
my apologies for the last comment. It does in fact work. Thanks again.
There is the "value" attribute on INPUT element. It would be much simpler with it...
Thanks for this. I thought I was going mad! Good tip :)
Now if only I can set the radio buttons... Coming from C to javascript is ugly, I'm not fond of loosely type variables.
How would you use this with multiple checkboxes
Post a Comment