I am currently facing an issue where I am unable to set a input box to stay checked after a refresh. I have stored the values in the local storage, even though the value is stored in the local storage; the checkbox does not remain checked. Please do help me on this! Thank you
Here is the html code:
<div style="color: #005e95">
<input type="checkbox" id="checkboxFullDownload" data-dojo-attach-event="onClick: _test" style="cursor: pointer;" >
Full Download
</div>
Here is the JS code:
_test: function(){
let checkBox = document.getElementById("checkboxFullDownload")
if(localStorage.getItem(`${xmlTitle} ID:${this.item._id}`) === "AllowFullDownload"){
checkBox.setAttribute("checked",true)
console.log("set to true")
}
if(checkBox.checked){
console.log("Checked")
localStorage.setItem(`${xmlTitle} ID:${this.item._id}`,"AllowFullDownload")
checkBox.checked = true;
}
if(!checkBox.checked){
console.log("Unchecked")
localStorage.removeItem(`${xmlTitle} ID:${this.item._id}`)
checkBox.setAttribute("checked",false)
}
}
If you want to check the checkbox on pageload then localStorage.getItem()
must be out of scope of any functions which are executed on certain events.
let checkBox = document.getElementById("checkboxFullDownload");
_test: function() {
if (checkBox.checked) {
console.log("Checked");
localStorage.setItem(`${xmlTitle} ID:${this.item._id}`, "AllowFullDownload");
checkBox.checked = true;
}
if (!checkBox.checked) {
console.log("Unchecked");
localStorage.removeItem(`${xmlTitle} ID:${this.item._id}`);
checkBox.checked = false;
}
}
if (localStorage.getItem(`${xmlTitle} ID:${_test.item._id}`) === "AllowFullDownload") {
checkBox.checked = true;
console.log("set to true");
}