1

I got the following code from W3Schools, but am wondering how to get the checkbox value to persist even after page reload:

Keep HTML: <input type="checkbox" ng-model="myVar">

<div ng-if="myVar">
<h1>Welcome</h1>
<p>Welcome to my home.</p>
<hr>
</div>

<p>The DIV element will be removed when the checkbox is not checked.</p>
<p>The DIV element will return, if you check the checkbox.</p>

Right now, if you check the box and reload the page, the checkbox becomes unchecked again.

How would you get the checkbox to retain its value even after reload? Thanks!

2
  • 2
    You have to persist the value somewhere. Whether that is client-side or server-side and the method by which you persist it is up to you. Commented Jun 24, 2019 at 22:43
  • You could use localStorage. Commented Jun 25, 2019 at 8:57

1 Answer 1

1

localStorage would store your information even if you restart the browser... i think this will be more suited... the following code would work for you in your local environment

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {

  let existingStoredValue = localStorage.getItem("checkBox Value");
  if (existingStoredValue == 'true') {
    $scope.myVar = true;
  }

  $scope.storeCB = function(passedVal) {
    localStorage.setItem("checkBox Value", passedVal);
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">

  Keep HTML: <input id='keepHTML' type="checkbox" ng-model="myVar" ng-click="storeCB(myVar)">

  <div ng-if="myVar">
    <h1>Welcome</h1>
    <p>Welcome to my home.</p>
    <hr>
  </div>

  <p>The DIV element will be removed when the checkbox is not checked.</p>
  <p>The DIV element will return, if you check the checkbox.</p>
</div>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.