简体   繁体   中英

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 !

I reviewed your code and took the liberty to refactor some excerpts, I tried to keep it as similar as possible to what you did, you can see the result below.

HTML:

<input id="myCheckbox" type="checkbox" name="myCheckbox" />

JS:

// get the checkbox element
const myCheckbox = document.querySelector('#myCheckbox')

// responsible for setting a value in localStorage
// following the "checked" state
const setStorageState = (e) => {
  const { id, checked } = e.target
  localStorage.setItem(id, checked)
}

// responsible for searching and converting to Boolean
// the value set in localStorage
const getStorageState = (storageName) => {
  return localStorage.getItem(storageName) === 'true'
}

// responsible for changing the state of your checkbox
const setCheckboxStateOnLoad = () => {
  myCheckbox.checked = getStorageState('myCheckbox')
}

// calls the function "setStorageState" every time
// the user clicks on his checkbox
myCheckbox.addEventListener('click', setStorageState)

// calls the "setCheckboxStateOnLoad" function
// after the DOM content is loaded
document.addEventListener('DOMContentLoaded', setCheckboxStateOnLoad)

Hope it helps and sorry for the bad english:)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM