0

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>
  • CodePen automatically executes your JS _after_ the DOM is ready. Your HTML does not. Your “loading” part happens before any checkbox exists. The current best practice is to include your JavaScript code as a [module](//developer.mozilla.org/en/docs/Web/JavaScript/Guide/Modules) using `` which solves this problem and many more. – Sebastian Simon Feb 18 '23 at 17:39

0 Answers0