简体   繁体   中英

Unable to set Checkbox to Checked after refreshing and storing in Local Storage

I am currently facing an issue where I am unable to set a input box to stay checked after a refresh. I have stored the values in the local storage, even though the value is stored in the local storage; the checkbox does not remain checked. Please do help me on this! Thank you

Here is the html code:

      <div style="color: #005e95">
        <input type="checkbox" id="checkboxFullDownload" data-dojo-attach-event="onClick: _test" style="cursor: pointer;"  >
        Full Download
      </div>

Here is the JS code:

_test: function(){
        let checkBox = document.getElementById("checkboxFullDownload")

        if(localStorage.getItem(`${xmlTitle} ID:${this.item._id}`) === "AllowFullDownload"){
          checkBox.setAttribute("checked",true)
          console.log("set to true")
        }

        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.setAttribute("checked",false)
          }
}

If you want to check the checkbox on pageload then localStorage.getItem() must be out of scope of any functions which are executed on certain events.

 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");
}

checkBox.setAttribute("checked",true)替换为checkBox.checked = true

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