0

Can I save the value of the check mark box so when the page is refreshed it will display accordingly if the box was checked before or not? This is for a To Do list app. I have been searching and reading MDN documents trying to figure out a solution, any help would be greatly appreciated. Thank you!

JavaScript

var masterList = [];

window.onload = function(){
  masterList = JSON.parse(localStorage.getItem('masterList')); //get data from storage
  if (masterList !== null) { //if data exist (todos are in storage)
    masterList.forEach(function(task){ //append each element into the dom
      var entry = document.createElement('li'); //2
      var list = document.getElementById('orderedList'); //2
      var text = document.createTextNode(task);
      var checkbox = document.createElement('input');
        checkbox.type = 'checkbox';
        checkbox.name = 'name';
        checkbox.value = 'value';
        checkbox.id = 'id';
        entry.appendChild(checkbox);
      document.getElementById('todoInput').appendChild(entry);
      list.appendChild(entry);
      entry.appendChild(text);
    })
  } else { //if nothing exist in storage, keep todos array empty
    masterList = [];
  }
}

function addToList(){

  var task = document.getElementById('todoInput').value;
  var entry = document.createElement('li'); //2
  var list = document.getElementById('orderedList'); //2
  var text = document.createTextNode(task);
  var checkbox = document.createElement('input');
    checkbox.type = 'checkbox';
    checkbox.name = 'name';
    checkbox.value = 'value';
    checkbox.id = 'id';
    entry.appendChild(checkbox);
  document.getElementById('todoInput').appendChild(entry);
  list.appendChild(entry);
  entry.appendChild(text);

  masterList.push(task);

  localStorage.setItem('masterList', JSON.stringify(masterList));

  console.log(task);
  console.log(masterList);
  clearInput();
}

function clearInput() {
    todoInput.value = "";
}

console.log((localStorage.getItem('masterList')));

EDIT - added rest of code HTML

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title></title>
    <link href="style.css" rel="stylesheet">
  </head>
  <body>

      <h1>To Do List:<h1>

        <input id="todoInput" type="text">
        <button type="button" onclick="addToList()">Add Item</button>
        <ol id='orderedList'></ol>

    <script src="todo.js"></script>

  </body>
</html>

CSS

ol li {
  background: lightgray;
  text-align: left;
}

ol li:nth-child(odd){
  background: lightblue;
  text-align: left
  text: 10%;
}

input[type=text]{
  width: 20%;
  border: 2px solid black;
  background-color: rgba(255, 0, 0, 0.2);
  text-align: center;
}

h1{
  text-align: center;
}
bemon
  • 113
  • 4
  • 14
  • 1
    Post whole code (: – kind user Mar 01 '17 at 20:40
  • You can use `localStorage` to save the value of a check box (assuming the browser allows it). Please post all of your code so we can see what's not working. – freginold Mar 01 '17 at 20:43
  • I have posted all of my code, I cannot find the starting point for saving the check box information. Would I have to create a new function or is it something I would want to add into what I already have? – bemon Mar 01 '17 at 20:46
  • See [this article](https://www.smashingmagazine.com/2010/10/local-storage-and-how-to-use-it/) for a good basic tutorial on using `localStorage`... it will show you how to set and retrieve values. – freginold Mar 01 '17 at 20:49
  • @bemon Did you get good answer or should I add one? – kind user Mar 01 '17 at 21:29
  • I appreciate all the answers and help but @kind user if you are able to show me like you did before, that would be great as then I can how to works for future reference as when reading everything it still kind of seems like gibberish until I see how it's done. – bemon Mar 01 '17 at 21:57

3 Answers3

1

Sorry for the delay, but was kinda complicated.

If you wonder what have I done here - I've changed the method of storing your todos. It used to be just a basic array ['one', 'two', 'three']. Now it is an array of objects:

[{todo: 'one', isChecked: false}, {todo: 'one', isChecked: false}].

When specified checkbox is checked, an event listener is changing the value of isChecked key of specified object (corresponding to the clicked checkbox) and stores the data inside the local storage.

var masterList = [];

window.onload = function() {
    masterList = JSON.parse(localStorage.getItem('masterList')); //get data from storage
    if (masterList !== null) { //if data exist (todos are in storage)
        masterList.map(function(task) { //append each element into the dom
            var entry = document.createElement('li'); //2
            var list = document.getElementById('orderedList'); //2
            var text = document.createTextNode(task.todo);
            var checkbox = document.createElement('input');
            checkbox.type = 'checkbox';
            checkbox.name = 'name';
            checkbox.value = 'value';
            checkbox.id = 'id';
            checkbox.className = 'x';
            checkbox.checked = task.isCheckboxChecked;
            entry.appendChild(checkbox);
            document.getElementById('todoInput').appendChild(entry);
            list.appendChild(entry);
            entry.appendChild(text);
        })
    } else { //if nothing exist in storage, keep todos array empty
        masterList = [];
    }

    var checkboxes = document.getElementsByClassName('x');
    Array.from(checkboxes).forEach((v, i) => v.addEventListener('click', function() {
        masterList[i].isCheckboxChecked == false ? masterList[i].isCheckboxChecked = true : masterList[i].isCheckboxChecked = false;
        localStorage.setItem('masterList', JSON.stringify(masterList));
    }));

}

function addToList() {

    var task = document.getElementById('todoInput').value;
    var entry = document.createElement('li'); //2
    var list = document.getElementById('orderedList'); //2
    var text = document.createTextNode(task);
    var checkbox = document.createElement('input');
    checkbox.type = 'checkbox';
    checkbox.name = 'name';
    checkbox.value = 'value';
    checkbox.id = 'id';
    checkbox.className = 'x';
    entry.appendChild(checkbox);
    document.getElementById('todoInput').appendChild(entry);
    list.appendChild(entry);
    entry.appendChild(text);
    var obj = {};
    obj.todo = task;
    obj.isCheckboxChecked = false;

    masterList.push(obj);

    localStorage.setItem('masterList', JSON.stringify(masterList));

    console.log(task);
    console.log(masterList);
    clearInput();
    var checkboxes = document.getElementsByClassName('x');
    console.log(Array.from(checkboxes))
    Array.from(checkboxes).forEach((v, i) => v.removeEventListener('click', function() {
        masterList[i].isCheckboxChecked == false ? masterList[i].isCheckboxChecked = true : masterList[i].isCheckboxChecked = false;
    }));
    Array.from(checkboxes).forEach((v, i) => v.addEventListener('click', function() {
        masterList[i].isCheckboxChecked == false ? masterList[i].isCheckboxChecked = true : masterList[i].isCheckboxChecked = false;
        localStorage.setItem('masterList', JSON.stringify(masterList));
    }));
}

function clearInput() {
    todoInput.value = "";
}
kind user
  • 40,029
  • 7
  • 67
  • 77
  • 1
    Thank you for all of the help today. You have been instrumental to my learning of JavaScript today. No worries on the 'delay', I greatly appreciate your help. – bemon Mar 01 '17 at 23:21
0

You probably want cookies (document.cookie). Have a look:
https://www.w3schools.com/js/js_cookies.asp
https://developer.mozilla.org/en-US/docs/Web/API/Document/cookie

But be careful . . . It's weird!
How exactly does document.cookie work?

Community
  • 1
  • 1
Justin Taddei
  • 2,142
  • 1
  • 16
  • 30
-1

You need to handle the change event of the checkbox and persist the data by yourself, maybe in localStorage. It could be an array of key value pairs with checkbox name and checked state.

After postback on form load, get your data back and restore the state of checkboxes from previous saved data.

Oscar
  • 13,594
  • 8
  • 47
  • 75