0

I am just starting with programming and I am playing around with this todo list. Now I want to add my todo items to local storage.

But everytime I add a new item to the list I overwrite the one and only to do item.

How do I solve this?

Here is the code:

$(document).ready(function() {
  var data = JSON.parse(localStorage.getItem("todoData"));

  for (var i = 0; i < localStorage.length; i++) {
    $('#thingsTodo').append('<div class="section">' +
      '<li id="listItem" class="blue-text text-darken-2 tooltip">' + data + '<span class="tooltiptext">Click to edit</span></li>' +
      '<i class="small material-icons deleteThisItem">delete</i>' +
      '<div class="divider"></div>');
  }

  $('#addItem').on('click', addItemToList);
  $('#thingsTodo').on('click', '.deleteThisItem', deleteItem);
  $('#thingsTodo').on('click', '#listItem', editItem);

  function addItemToList() {
    var newItem = {
      value: $('#inputField').val()
    };

    if (newItem.value !== '') {

      localStorage.setItem("todoData", JSON.stringify(newItem.value));

      $('#thingsTodo').append('<div class="section">' +
        '<li id="listItem" class="blue-text text-darken-2 tooltip">' + newItem.value + '<span class="tooltiptext">Click to edit</span></li>' +
        '<i class="small material-icons deleteThisItem">delete</i>' +
        '<div class="divider"></div>');
      $('#inputField').val("");
    } else {
      alert("Please make sure you enter something before clicking the button");
    }
  }

  function deleteItem() {
    $(this).closest('.section').remove();
    $(this).closest('.divider').remove();
  }

  function editItem() {
    var newTodoInput = {
      newValue: prompt("Please edit your todo item")
    };


    if (typeof newTodoInput.newValue !== 'object') {
      if (newTodoInput.newValue !== "") {

        $(this).replaceWith('<li id="listItem" class="blue-text text-darken-2 tooltip">' + newTodoInput.newValue + '<span class="tooltiptext">Click to edit</span></li>');
      }

    } else {
      alert("Please make sure you enter something before clicking the button");
    }


  }

});

If possible please also show me how to save it when I edit a list item.

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
Wolfyr
  • 409
  • 3
  • 11
  • Possible duplicate of [adding new objects to localstorage](https://stackoverflow.com/questions/12162786/adding-new-objects-to-localstorage) – Heretic Monkey Mar 02 '18 at 00:50
  • I did found that post before I posted mine, but I can't seem ti get it working... – Wolfyr Mar 02 '18 at 00:57
  • Then [edit] your question to include how you implemented the suggestions in the answers an how they didn't work. – Heretic Monkey Mar 02 '18 at 00:59
  • I tried a 100 things so far.... Not realy saved every thing I tried so far... So not realy an option. Sorry – Wolfyr Mar 02 '18 at 01:00
  • Almost finished, I have it now, so that it saves more then 1 item, but it will only save everything from your last sesion. – Wolfyr Mar 02 '18 at 01:08

2 Answers2

1

When you create a new to do item you could push that item to a global array then add at that array to your local store like this.

 var items = [];


 function addItemToList (){
  var input = $('#inputField').val() 
  items.push(input);

  if(input){
    localStorage.setItem("todoData", JSON.stringify(items));

            $('#thingsTodo').append('<div class="section">'+
             '<li id="listItem" class="blue-text text-darken-2 tooltip">'   + item + '<span class="tooltiptext">Click to edit</span></li>'+
                        '<i class="small material-icons deleteThisItem">delete</i>'+
                        '<div class="divider"></div>');

    $('#inputField').val("");
    }else{
      alert("Please make sure you enter something before clicking the button");
 }
}

Use localStorage.setObj(key, value) to save an array or object and localStorage.getObj(key) to retrieve it like this

 $(document).ready(function() {
 var storedItems = JSON.parse(localStorage.getItem("toDoData"));

        for(var i = 0; i < storedItems.length; i++) {
                       $('#thingsTodo').append('<div class="section">'+
         '<li id="listItem" class="blue-text text-darken-2 tooltip">'   + storedItems[i] + '<span class="tooltiptext">Click to edit</span></li>'+
                    '<i class="small material-icons deleteThisItem">delete</i>'+
                    '<div class="divider"></div>');
        }
      });
radlaz
  • 298
  • 4
  • 16
  • I can't seem to get it to work. Note the my newInput var is made into an object. Maybe if I cange it back to a normal var? I also tried items.push(newInput.value); – Wolfyr Mar 02 '18 at 00:04
  • Copy and paste my code exactly for the addToDoItem function and it should work(note that I haven't tested it). then at the bottom is to access that array using JASON.parse(localStorage.getItem) convert the string back to an array. Localstorage can only hold strings This is why you use json.stringify to save that array to local storage. And I say an array is the easiest way to go about this. It would just require a little changing on how you have the items rendered to the dom. – radlaz Mar 02 '18 at 00:12
  • And my apologies for any typos or formatting I'm on mobile – radlaz Mar 02 '18 at 00:15
  • I tried to copy and paste it, but it doesn't work (I guess with the rest of the code). Still playing around with it... Will get it eventualy haha – Wolfyr Mar 02 '18 at 00:20
  • Haha no worries about that ;) and thanks for the help so far – Wolfyr Mar 02 '18 at 00:20
  • I kept my objects. And it only stores the last added items now (so if I add some and reload, items I added before are lost). But its a good start and your code did the trick. So basicly I did items.push(newItem.value); And appended it also with newItem.value – Wolfyr Mar 02 '18 at 01:20
0

In youraddItemToList function you are using always the same key for all question. It's normal behavior that it overrides the existing one. You must either store your todo items in an array under the same key or have different keys for each item.

Simplified code for array.

var initialTodos = [];
localStorage.setItem('todoData', JSON.stringify(initialTodos );

// add item
function addItem(item) {
  var todos = getTodos();
  todos.push(item);
  localStorage.setItem('todoData', JSON.stringify(todos));
}
 // remove get data
function getTodos() {
   return JSON.parse(localStorage.getItem('todoData'));
}
// remove item
function removeItem(item) {
   var todos = getTodos();
   var index = todosFromStorage.indexOf(item);
   if (index >= 0) {
       todos.splice(index, 1);
       localStorage.setItem('todoData', JSON.stringify(todos));
   }
}

If you want to use different values. Add a unique id field to each item and use it for the key.

localStorage.setItem("todoData" + Date.now(), JSON.stringify(newItem.value));

Note: Don't use iterate over localStorage fields, because you can potentially have other types of data also stored.

ztadic91
  • 2,774
  • 1
  • 15
  • 21
  • I tried to implement the above. But I get an error data.push() is not a function. Also can I implement this without changing 90% of my code? Must be an other way right? – Wolfyr Mar 01 '18 at 23:01
  • It might help if you didn't have 3 differently scoped variables named `data` in your code. – connexo Mar 01 '18 at 23:50
  • I only have 1 variable called data? Only in the top of my code for the localstorage.get. – Wolfyr Mar 02 '18 at 00:02