I have been trying to create a completion tracker where I can use checkboxes to track tasks I have to do. I would like the checkboxes to remain checked. However the only place where I can get this to happen with my current code is in codepen.io . When I open with live server or open in browser using the extensions in vscode, it has not remembered that I have checked the boxes. How can I fix this?
This is my javascript file (app.js):
let boxes = document.getElementsByClassName('box').length;
function save() {
for(let i = 1; i <= boxes; i++){
var checkbox = document.getElementById(String(i));
localStorage.setItem("checkbox" + String(i), checkbox.checked);
}
}
//for loading
for(let i = 1; i <= boxes; i++){
if(localStorage.length > 0){
var checked = JSON.parse(localStorage.getItem("checkbox" + String(i)));
document.getElementById(String(i)).checked = checked;
}
}
window.addEventListener('change', save);
And this is the html file:
<script src="app.js"></script>
<input type="checkbox" id="1" class="box">checkbox1</input><br>