mercredi 1 mars 2017

Saving check mark in JavaScript on page refresh

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;
}




Aucun commentaire:

Enregistrer un commentaire