vendredi 19 mai 2023

how do I keep checkboxs stay checked after refreshing the page?

I am studying how to keep checkboxs stay checked after refreshing the page. And I find this helps. However, the code, does not work right at my server. When I refresh, checkboxs stayed unchecked. I also use this compiler. NOT GOOD. See

The code I use:

<!DOCTYPE html>
<html>
<head>
<style type="text/css">
#checkbox-container{
  margin: 10px 5px;
}

#checkbox-container div{
  margin-bottom: 5px;
}

#checkbox-container button{
  margin-top: 5px;
}

input[type=text] {
  padding: .5em .6em;
  display: inline-block;
  border: 1px solid #ccc;
  box-shadow: inset 0 1px 3px #ddd;
  border-radius: 4px;
}
</style>
</head>

<body>
<div id="checkbox-container">
  <div>
    <label for="option1">Option 1</label>
    <input type="checkbox" id="option1">
  </div>
  <div>
    <label for="option2">Option 2</label>
    <input type="checkbox" id="option2">
  </div>
  <div>
    <label for="option3">Option 3</label>
    <input type="checkbox" id="option3">
  </div>
</div>
</body>


</html>
<script>
    var checkboxValues = JSON.parse(localStorage.getItem('checkboxValues')) || {},
    $checkboxes = $("#checkbox-container :checkbox");
    
    $checkboxes.on("change", function(){
      $checkboxes.each(function(){
        checkboxValues[this.id] = this.checked;
      });
      
      localStorage.setItem("checkboxValues", JSON.stringify(checkboxValues));
    });
    
    // On page load
    $.each(checkboxValues, function(key, value) {
      $("#" + key).prop('checked', value);
    });
</script>

It seems to me that the code only works on CODEPEN. May somebody tells me what is wrong? Thanks a lot.




Aucun commentaire:

Enregistrer un commentaire