mercredi 13 mai 2020

How to check/uncheck checkbox based on localStorage state

I'm trying to persist checkbox state in a HTML (Flask/Jinja2) template using just html and CSS, but I've running into strange behavior where even though localStorage saves the state correctly, state is always set as true on load. I've looked up a ton of answers and have been stuck for a couple hours and I don't understand it isn't working:

HTML:

<input id="returnHeatmapsHtmlCheckbox" 
type="checkbox" name="returnHeatmapsHtml" onclick="saveCheckboxState(this)" /> 

JS:

<script type="text/javascript">
    window.onload = onPageLoad();
      function onPageLoad (){
document.getElementById("returnHeatmapsHtmlCheckbox").checked = localStorage.getItem("returnHeatmapsHtmlCheckbox");
}
// <!-- Persist checkboxes  -->
      function saveCheckboxState(e){
        var id = e.id
        var val = e.checked
        console.log("Saved value ID: " + id + ","+ val)
        localStorage.setItem(id,val)
        console.log("Loaded value ID: " + localStorage.getItem(id,val))
        console.log(getSavedCheckboxState("returnHeatmapsHtmlCheckbox"))
      }
      function getSavedCheckboxState(v){
        const default_dict = {
          "returnHeatmapsHtmlCheckbox": false
        };

        if (!localStorage.getItem(v)) {
          return default_dict[v];// return false by default. 
        };
        return localStorage.getItem(v);
      }
  </script>

Any help would be greatly appreciated, thank you !




Aucun commentaire:

Enregistrer un commentaire