javascript - Checkbox isn't checking to the correct value -
i have should simple code, reason i'm not getting wrong logic setting checkbox properly. i'm using local storage checked state persistent among sessions.
here code. happening reason though console.log
prints out false when should false, or true when should true, either way checkbox ends being checked.
var checkboxelement = document.getelementbyid("checkbox").getelementsbytagname('input')[0] checkboxelement.addeventlistener('click', function() { console.log(checkboxelement.checked) if (localstorage != undefined) { localstorage.setitem("checkbox", checkboxelement.checked) } }); if(localstorage != undefined) { console.log("local storage supported."); //set defaults if (localstorage.getitem("checkbox") == undefined) { localstorage.setitem("checkbox", false) } var ischecked = localstorage.getitem("checkbox") checkboxelement.checked = ischecked console.log(ischecked) }
because localstorage stores value string, when have false
, stored 'false'
truthy value if checkbox unchecked marked checked.
var ischecked = localstorage.getitem("checkbox") === 'true'; checkboxelement.checked = ischecked; console.log(ischecked)
demo: fiddle
Comments
Post a Comment