Good day everyone, I am currently facing some issues with my following code. Basically I want to keep my checkbox checked by using the key value pair value I stored in localStorage, so upon reload the checkbox should be checked (those with the key value pair). However, I kept getting this error. I have tried using window.onLoad but it did not work; any other solutions for this..? Please do let me know if there is anything wrong with my code too. Thank you
Error
Cannot set properties of null (setting 'checked')
Html Code:
<div style="color: #005e95">
<input type="checkbox" id="checkboxFullDownload" data-dojo-attach-event="onClick: _test" style="cursor: pointer;" >
Full Download
</div>
JS Code:
_test: function() {
let checkBox = document.getElementById("checkboxFullDownload");
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");
}
let keyword is block scope once declared in scope cannot be accessed outside of that scope.
In your case let keyword is in the scope of _test: function(){}. By moving it outside will do the work.
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");
}