Skip to content Skip to sidebar Skip to footer

Save Checkbox Value With Javascript The Easy Way?

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

Solution 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

Solution 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:

<inputtype="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.

Post a Comment for "Save Checkbox Value With Javascript The Easy Way?"