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.