jeudi 23 février 2023

Checkboxes become unchecked after going back to the previous page

I want to be able to save the values of the checkboxes and have the already checked ones displayed as checked even after I go back to the previous page and again to the next page. In all cases, I do not want the checked boxes to disappear. Here is what I have written as for the HTML code:

<style>
    .add-margin {
        margin-top:10px !important;
    }
</style>
<div>
    <div ng-init="loaded()" ng-class="{'add-margin': descriptionsAvailable}" class="checkbox-inline" ng-repeat="opt in options track by $index">
        <label style="direction:ltr;">
            <input ng-disabled="answer['none']" class="save-cb-state" type="checkbox" ng-model="answer[opt]" ng-true-value="true" ng-false-value="false" name="checkbox-answer-input" display= "inline-block", style = "width: 15px; padding: 0; margin: 0; position: relative; top: 0px; align-items: center;">
            <span></span><br/>
            <span><i></i></span>
        </label>
      </div>

</div>

Here is the JavaScript code:

function() {
  // variable to store our current state
  var cbstate;

  // bind to the onload event
  window.addEventListener('load', function() {
    // Get the current state from localstorage
    // State is stored as a JSON string
    cbstate = JSON.parse(localStorage['CBState'] || '{}');

    // Loop through state array and restore checked
    // state for matching elements
    for(var i in cbstate) {
      var el = document.querySelector('input[name="' + i + '"]');
      if (el) el.checked = true;
    }

    // Get all checkboxes that you want to monitor state for
    var cb = document.getElementsByClassName('save-cb-state');

    // Loop through results and ...
    for(var i = 0; i < cb.length; i++) {

      //bind click event handler
      cb[i].addEventListener('click', function(evt) {
        // If checkboxe is checked then save to state
        if (this.checked) {
          cbstate[this.name] = true;
        }

    // Else remove from state
        else if (cbstate[this.name]) {
          delete cbstate[this.name];
        }

    // Persist state
        localStorage.CBState = JSON.stringify(cbstate);
      });
    }
  });
})();

However, when I go back to the previous page, the previously checked boxes are unchecked. This holds true as well when proceeding to the next page again.




Aucun commentaire:

Enregistrer un commentaire