Save checkbox value with javascript the easy way?

梦想的初衷 提交于 2019-12-11 05:31:48

问题


I got a couple of questions. My javascript/coding game is still a very VERY beginner I don't understand the 'save checkbox value' questions that are already on this site.

I think the solution is really simple, but there are a couple of questions I have.

Let me explain my idea/problem: Since I'm trying to learn javascript by adding new functions to an existing script I've found on the angularJS website I stumbled on some things I couldn't figure out myself.

I've got this list of checkboxes and want to save the checkbox input. When visiting the page the checkboxes are all empty. When I check one of the boxes I got this little msg saying something like 'well done!'. When I refresh the page the box is empty again. I want to save the user input so the checkbox stays checked.

My code: HTML:

          <div ng-controller="TodoListController as todoList">         
        <span>Nog {{todoList.remaining()}} van de {{todoList.todos.length}} te gaan!</span>
        <!--[ <a href="" ng-click="todoList.archive()">archive</a> ]-->
        <ul class="unstyled">
          <div class="column">
          <li ng-repeat="todo in todoList.todos">
            <label class="checkbox">
              <input type="checkbox" onclick="alert('Well done!')" ng-model="todo.done" ng-disabled="todo.done"> 

              <span class="done-{{todo.done}}">{{todo.text}}</span>

            </label>
          </li>
          </div>
        </ul>
      </div> <!--end ng-controller -->

Javascript/AngularJS:

angular.module('todoApp', [])
.controller('TodoListController', function() {
var todoList = this;
todoList.todos = [
  {text:'Leer HTML5', done:true},
  {text:'Leer CSS3', done:true},
  {text:'Leer Javascript', done:false},
  ];

todoList.remaining = function() {
  var count = 0;
  angular.forEach(todoList.todos, function(todo) {
    count += todo.done ? 0 : 1;
  });
  return count;
};

todoList.archive = function() {
  var oldTodos = todoList.todos;
  todoList.todos = [];
  angular.forEach(oldTodos, function(todo) {
    if (!todo.done) todoList.todos.push(todo);
  });
};
});

I've read a lot of questions other people had and I don't really understand all the options to achieve this. I've found this little Fiddle code which is exactly what I'm looking for: http://jsfiddle.net/R73vy/ When I copy this code in my own Html and js files, it's not working. This code uses the client side to storage data by using cookies. How can I use this working code myself? What am I missing? Is it possible to achieve this with my existing code?

Thanks in advance and excuse my level of an absolute beginner. If you got questions, let me know!


回答1:


If you want to save some values after your web page is refreshed (when we speaking about client side only), you should use storage or cookies, depends on goal you want to achieve. When you refresh page, all your javascript code is rebooting and all variables are refresing, so you cannot use them to save some data or values. Different frameworks have their own methods, which allow you to save some data when page is refreshing. It can be localStorage or sessionStorage, if you want to use pure JS. $cookies if you want to use Angular will help you to save your model and display its values after refresh. And also there is some discussion I found, may be interesting for you localStorage vs sessionStorage vs cookies




回答2:


The piece script you are referencing on jsfiddle.net is using $.cookie. Which is jquery + a cookie plugin.

For some reason people prefer to limit usage of jquery with Angular. A good discution about it is available here: "Thinking in AngularJS" if I have a jQuery background?

In your case you I will advice you usage of local storage instead of cookie. Some explanations are available here: Local Storage vs Cookies

Then the idea is to install the angular-local-storage pakage via npm

Then you should change your code to something like this:

angular.module('todoApp', [])
  .controller('TodoListController', function(localStorageService) {
  var todoList = this;
  todoList.todos = [
    {text:'Leer HTML5', done:localStorageService.get('todo1'), id:'todo1'},
    {text:'Leer CSS3', done:localStorageService.get('todo2'), id:'todo2'},
    {text:'Leer Javascript', done:localStorageService.get('todo3'), id:'todo2'},
  ];

  todoList.onClickItem = function(todoId) {
    if (localStorageService.get( todoId ) {
      localStorageService.set( todoId, false);
    } else {
      localStorageService.set( todoId, true);
    }
  }

  todoList.remaining = function() {
    var count = 0;
    angular.forEach(todoList.todos, function(todo) {
      count += todo.done ? 0 : 1;
    });
    return count;
  };

  todoList.archive = function() {
    var oldTodos = todoList.todos;
    todoList.todos = [];
    angular.forEach(oldTodos, function(todo) {
      if (!todo.done) todoList.todos.push(todo);
    });
  };
});

and update the view as:

<input type="checkbox" onclick="onClickItem('{{todo.todoId}}');" ng-model="todo.done" ng-disabled="todo.done"> 

This code may not work straight away. But that to show the direction to the solution.



来源:https://stackoverflow.com/questions/44589201/save-checkbox-value-with-javascript-the-easy-way

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!