acbrent25
9/4/2017 - 5:30 PM

To Do List with Local Storage

To Do List with Local Storage

<!DOCTYPE html>
<html lang="en-us">

<head>

  <meta charset="UTF-8">
  <title>Local Storage To-Do List</title>
</head>

<body>

  <h1>To-Do List Persisted with Local Storage</h1>

  <form>
    <input type="text">
    <input type="submit" value="save">
  </form>

  <div id="todo-list"></div>

  <script src="https://code.jquery.com/jquery-2.2.1.min.js"></script>
  <script type="text/javascript">
    var list = []

    // Checks to see if the todolist exists in localStorage and is an array currently
    // If not, set a local list variable to an empty array
    // Otherwise list is our current list of todos

    function putOnPage() {

      $("#todo-list").empty(); // empties out the html

      list = JSON.parse(localStorage.getItem("todolist"));

      // Checks to see if the todolist exists in localStorage and is an array currently
      // If not, set a local list variable to an empty array
      // Otherwise list is our current list of todos
      if (!Array.isArray(list)) {
        list = [];
      }

      // render our insideList todos to the page
      for (var i = 0; i < list.length; i++) {
        var p = $("<p>").text(list[i]);
        var b = $("<button class='delete'>").text("x").attr("data-index", i);
        p.prepend(b);
        $("#todo-list").prepend(p);
      }
    }

    // render our todos on page load
    putOnPage();

    $(document).on("click", "button.delete", function () {
      var todolist = JSON.parse(localStorage.getItem("todolist"));
      var currentIndex = $(this).attr("data-index");

      // Deletes the item marked for deletion
      todolist.splice(currentIndex, 1);
      list = todolist;

      localStorage.setItem("todolist", JSON.stringify(todolist));

      putOnPage();
    });

    $("input[type='submit']").on("click", function (event) {
      event.preventDefault();
      // Setting the input value to a variable and then clearing the input
      var val = $("input[type='text']").val();
      $("input[type='text']").val("");

      // Adding our new todo to our local list variable and adding it to local storage
      list.push(val);
      localStorage.setItem("todolist", JSON.stringify(list));

      putOnPage();
    });
  </script>
</body>

</html>