skip to Main Content

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.

2

Answers


  1. <!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: 0.5em 0.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>
    
        <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
        <script>
          $(document).ready(function () {
            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>
      </body>
    </html>
    
    

    The code you provided has a couple of issues:

    1. The script tag is placed outside the HTML body. Move the script tag inside the body or wrap the JavaScript code in a proper script block.

    2. The jQuery library is not included in the code. To use jQuery functions like $(), you need to include the jQuery library before using it.

    Login or Signup to reply.
  2. Why not use a fieldset and track changes to the entire thing?

    enter image description here

    • No jQuery dependency
    • Simplifies HTML
    • Only adds one listener

    I’ve also genericized the listener so that it can easily be modified to handle more fieldsets as well as other input types. input type="text" support added as an example.

    window.addEventListener("load", (event) => {
        restoreChanges("fieldset1");
        trackChanges("fieldset1");
    });
    
    // Reads localStorage back into fieldset's inputs 
    function restoreChanges(fieldsetId) {
        var json = localStorage.getItem(fieldsetId);
        if(json) {
            JSON.parse(json).forEach(item => {
                if(typeof item.value == "boolean") {
                    // Handle checkbox
                    document.getElementById(item.id).checked = item.value;
                } else {
                    document.getElementById(item.id).value = item.value;
                }
            });
        }
    }
    
    // Automatically saves fieldset's inputs to localStorage
    function trackChanges(fieldsetId) {
        // Add listener to entire fieldset
        document.getElementById(fieldsetId).addEventListener('change', (event) => {
            var inputValues = [];
            var inputs = event.currentTarget.getElementsByTagName("input");
            Array.from(inputs).forEach(element => inputValues.push(
                {
                    type: "input",
                    id: element.id,
                    value: element.type == "checkbox" ? element.checked : element.value
                }
            ));
            localStorage.setItem(event.currentTarget.id, JSON.stringify(inputValues));
            console.debug(inputValues);
        });
    }
    <!DOCTYPE html>
    <html>
      <body>
        <fieldset id="fieldset1">
            <legend>Choose your options</legend>
            <input type="checkbox" id="option1" />
            <label for="option1">Option 1</label><br/>
    
            <input type="checkbox" id="option2" />
            <label for="option2">Option 2</label><br/>
    
            <input type="checkbox" id="option3" />
            <label for="option3">Option 3</label><br/>
    
            <label for="option4">Option 4</label>
            <input type="text" id="option4" /><br/>
        </fieldset>
      </body>
    </html>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search