I'm having an issue with localStorage. Whenever the X (e.target.tagName === 'I') icon is clicked to remove one single item from localStorage, all of localStorage is cleared. What's going on? Any suggestions will be appreciated.
Javascript File
const todoInput = document.querySelector('#todo-item')
const todoList = document.querySelector('.todo-list')
const form = document.querySelector('form')
const todos = []
const savedTodos = JSON.parse(localStorage.getItem('todos')) || []
for (let i = 0; i < savedTodos.length; i++) {
let newTodo = document.createElement('LI')
newTodo.innerText = savedTodos[i]
newTodo.classList.add('todo-item')
const deleteBtn = document.createElement('I')
deleteBtn.classList.add('fa-sharp', 'fa-solid', 'fa-square-xmark')
newTodo.append(deleteBtn)
todoList.appendChild(newTodo)
}
form.addEventListener('submit', function (e) {
// e.preventDefault()
const newTodo = document.createElement('li')
newTodo.innerText = todoInput.value
newTodo.classList.add('todo-item')
const deleteBtn = document.createElement('i')
deleteBtn.classList.add('fa-sharp', 'fa-solid', 'fa-square-xmark')
newTodo.append(deleteBtn)
todoList.appendChild(newTodo)
todoInput.value = ''
todos.push(newTodo.innerText)
console.log(newTodo.innerText)
localStorage.setItem('todos', JSON.stringify(todos))
})
function removeFromStorage(itemToRemove) {
for (let i = 0; i < todos.length; i++) {
if (todos[i] === itemToRemove) {
todos.splice(i, 1)
}
}
localStorage.setItem('todos', JSON.stringify(todos))
}
todoList.addEventListener('click', function (e) {
// When this line of code is run all local storage is deleted
if (e.target.tagName === 'I') {
e.target.parentElement.remove()
removeFromStorage(e.target.parentElement.innerText)
} else if (e.target.tagName === 'LI') {
e.target.classList.toggle('todo-complete')
}
console.log(e.target.innerText)
})
Related
I was working on the todo list project, but while transferring the values written to the local storage to the UI, I encountered this error. I tried all the suggestions, but I could not do anything. What should I do?
Here is my code:
const form = document.querySelector("#todo-form");
const todoInput = document.querySelector("#todo");
const todoList = document.querySelector(".list-group");
const firstCard = document.querySelectorAll(".card-body")[0];
const secondCard = document.querySelectorAll(".card-body")[1];
const filter = document.querySelector("#filter");
const clearButton = document.querySelector("#clear-todos");
eventListeners();
function eventListeners() {
form.addEventListener("submit", addTodo);
document.addEventListener("DOMContentLoaded", loadAllTodosToUI);
}
function loadAllTodosToUI() {
let todos = getTodosFromStorage();
todos.forEach(function (todo) {
addTodoToUI(todo)
});
}
function addTodo(e) {
const newTodo = todoInput.value.trim();
if (newTodo === "") {
showAlert("danger", "bir todo gir");
} else {
addTodoToUI(newTodo);
addTodoToStorage(newTodo);
showAlert("success", "başarıyla eklendi");
}
e.preventDefault();
}
function getTodosFromStorage() {
let todos;
if (localStorage.getItem("todos") === null) {
todos = [];
} else {
todos = JSON.parse(localStorage.getItem(todos));
}
return todos;
}
function addTodoToStorage(newTodo) {
let todos = getTodosFromStorage();
todos.push(newTodo);
localStorage.setItem("todos", JSON.stringify(todos));
}
function showAlert(type, message) {
const alert = document.createElement("div");
alert.className = `alert alert-${type}`;
alert.textContent = message;
firstCard.appendChild(alert);
setTimeout(() => {
alert.remove();
}, 1000);
}
function addTodoToUI(newTodo) {
const listItem = document.createElement("li");
const link = document.createElement("a");
link.href = "#";
link.className = "delete-item";
link.innerHTML = "<i class = 'fa fa-remove'></i>";
listItem.className = "list-group-item d-flex justify-content-between";
listItem.appendChild(document.createTextNode(newTodo));
listItem.appendChild(link);
todoList.appendChild(listItem);
todoInput.value = "";
}
The console says that there is an error directly related to forEach, but the value I entered in the local storage is not null, but I get this error
i have an array named todoList, all of my data is in it.
i saved them to localstorage like this:
https://codepen.io/arashkazerouni/pen/YzLxdoQ
const saveToLocal = (array) => {
window.localStorage.setItem("todo", JSON.stringify(array));
};
todoList = JSON.parse(window.localStorage.getItem("todo"));
i used this saveToLocal function after any change in todoList, and it works.
the only problem is when i refresh the page, all items gone.
but if i add new todo, all of them will shown again
and there is page script :
const input = document.querySelector("input");
const button = document.querySelector("button");
const todos = document.querySelector(".todos");
const alertRed = document.querySelector(".alert-red");
let todoList = [];
const saveToLocal = (array) => {
window.localStorage.setItem("todo", JSON.stringify(array));
};
todoList = JSON.parse(window.localStorage.getItem("todo"));
const addToDOM = () => {
// todos.innerHTML = "";
for (let i = 0; i < todoList.length; i++) {
const html = `
<div class="todo" id=${i}>
<p class="todo-text" >${todoList[i]}</p>
<i class="fa-solid fa-check" ></i>
<i class="fa-solid fa-trash"></i>
</div>
`;
todos.insertAdjacentHTML("beforeend", html);
}
};
// Add items to list
button.onclick = (e) => {
e.preventDefault();
// todos.innerHTML = "";
if (!todoList.includes(input.value) && input.value !== "") {
todoList.push(input.value);
saveToLocal(todoList);
}
// console.log(todoList);
addToDOM();
input.value = "";
};
// Handle Enter Press
document.onkeypress = (e) => {
if (e.key === "Enter") {
button.click();
}
};
todos.onclick = (e) => {
e.preventDefault();
const isCheck = e.target.classList.contains("fa-check");
const isTrash = e.target.classList.contains("fa-trash");
if (isCheck) e.target.previousElementSibling.classList.toggle("checked");
if (isTrash) {
const element = e.target.parentElement;
const elementID = parseInt(element.id);
element.classList.add("removed");
todoList = todoList.filter((element) => element !== todoList[elementID]);
saveToLocal(todoList);
setTimeout(() => {
addToDOM();
}, 300);
}
};
import './style.css';
let newTask;
const arrowBtn = document.getElementById('arrow');
class Todolist {
constructor(description, completed, index) {
this.description = description;
this.completed = completed;
this.index = index;
}
addtask(dataBase) {
dataBase.push(this);
}
}
arrowBtn.addEventListener('click', () => {
const taskName = document.getElementById('input').value;
let dataBase = JSON.parse(localStorage.getItem('baseData'));
if (dataBase === null) {
dataBase = [];
}
const index = dataBase.length + 1;
newTask = new Todolist(taskName, false, index);
newTask.addtask(dataBase);
localStorage.setItem('baseData', JSON.stringify(dataBase));
document.location.reload();
document.preventDefault();
});
function displaytask() {
const dataBase = JSON.parse(localStorage.getItem('baseData'));
const unsortedList = document.querySelector('.list');
for (let i = 0; i < dataBase.length; i += 1) {
const list = document.createElement('li');
list.id = i + 1;
unsortedList.appendChild(list);
const checkbox = document.createElement('input');
checkbox.classList.add('check');
checkbox.type = 'checkbox';
list.appendChild(checkbox);
let span = document.createElement('input');
span.classList.add('span');
span.type = 'text';
span.value = dataBase[i].description;
list.appendChild(span);
const removeicon = document.createElement('button');
removeicon.classList.add('remove');
removeicon.innerHTML = '<i class="fa-solid fa-trash-can"></i>';
list.appendChild(removeicon);
removeicon.addEventListener('click', () => {
dataBase.splice(i, 1);
list.remove();
for (let i = 0; i < dataBase.length; i += 1) {
dataBase[i].index = i + 1;
}
localStorage.setItem('baseData', JSON.stringify(dataBase));
});
span.addEventListener('change', () => {
if (dataBase[i].description === 'change') {
dataBase[i].description = description.value;
}
localStorage.setItem('baseData', JSON.stringify(dataBase));
})
}
}
displaytask();
I want to change the values of the input from the list of tasks so that these are saved both in the list and in the local storage, I try with 'change' events but is not work.
this is when add to the list:
[https://i.stack.imgur.com/BOT6o.png]
this is when i want to change but is not saved:
[ https://i.stack.imgur.com/ZxoW8.png]
How can i make a delete function that deletes the specific list from local storage when delete button is clicked and update the data. I am a beginner and i have no idea how i can make this happen. I have tried to look for solution by watching video but i couldn't find solution that i can understand.
let input = document.querySelector('input');
let btn = document.querySelector('button');
let ul = document.querySelector('ul');
let arr = getItem() || [];
arr.forEach(renderItem);
function addItem() {
let inVal = input.value;
if (inVal === '') return;
renderItem(inVal);
arr.push(inVal);
setItem(arr);
input.value = '';
input.focus();
}
btn.addEventListener('click', () => {
addItem();
});
window.addEventListener('keydown', e => {
if (e.key === 'Enter') {
addItem();
}
});
function renderItem(render) {
let li = document.createElement('li');
li.innerText = render;
let del = document.createElement('button');
del.innerText = 'delete';
del.setAttribute('class', 'delete');
li.append(del);
ul.append(li);
}
function setItem(set) {
localStorage.setItem('name', JSON.stringify(arr));
}
function getItem() {
let result = localStorage.getItem('name');
return JSON.parse(result);
}
I am pretty much new to Javascript and working on this simple ToDo app that uses local storage to persist data. However, the Delete function can only delete from local storage when refreshed the page. What could be causing this bug? I have attached my code below
I tried commenting on the e.preventDefault() on the form but the page kept on reloading when a task is submitted.
// Selectors
const ul = document.querySelector('.todo-list');
const todoContainer = document.querySelector('.todo-container');
const clearButton = document.createElement('button');
clearButton.classList.add('clear-button');
clearButton.textContent = 'Clear all Completed';
const form = document.querySelector('.form');
const taskInput = document.querySelector('.todo-input');
let todoTasks = JSON.parse(localStorage.getItem('todo')) || [];
let id = todoTasks.length + 1;
const createElement = ({ description, completed = true, index }) => {
const todoItem = document.createElement('li');
todoItem.classList.add('todo-list-item');
todoItem.setAttribute('id', index);
todoItem.innerHTML = `
<input type="checkbox" class="check" value="${completed}">
<button class="hidden" name="${index}"></button>
<span class="todo-item">${description}</span>
<button name='eclips'><i class="fas fa-ellipsis-v"></i></button>
<button name='delete'><i class="fas fa-trash"></i></button>
`;
ul.appendChild(todoItem);
todoContainer.appendChild(ul);
todoContainer.appendChild(clearButton);
};
// get each todo task
todoTasks.forEach(createElement);
// Function that add todo
const addTask = (description, completed, ind) => {
const input = taskInput.value;
todoTasks.push({
description: input,
completed: false,
index: ind,
});
localStorage.setItem('todo', JSON.stringify(todoTasks));
return { description, completed, ind };
};
const checkTodo = (e) => {
const lineText = e.target.nextElementSibling.nextElementSibling.nextElementSibling;
if (lineText.style.textDecoration === 'line-through') {
lineText.style.textDecoration = 'none';
} else {
lineText.style.textDecoration = 'line-through';
lineText.classList.toggle('completed');
}
};
// Function that delete todo
const handleDeleteAndCheck = (e) => {
const item = e.target;
if (e.target.classList[1] === 'fa-trash') {
const todo = item.parentElement.parentElement;
const targetId = item.parentElement.parentElement.id;
todoTasks = todoTasks.filter((task) => task.index !== +targetId);
localStorage.setItem('todo', JSON.stringify(todoTasks));
todo.remove();
}
if (e.target.classList === 'check') {
checkTodo();
}
};
// Function that Edit todo
const editTask = (e) => {
const item = e.target;
if (item.classList[0] === 'todo-item') {
item.contentEditable = true;
item.style.display = 'block';
}
};
const check = document.querySelectorAll('.fa-check-square');
const index = document.querySelectorAll('#index');
form.addEventListener('submit', (e) => {
e.preventDefault();
const input = taskInput.value;
const checkValue = check.value;
// const indexValue = index.value;
const newTask = addTask(input, checkValue, id);
createElement(newTask);
// location.reload();
taskInput.value = '';
id += 1;
});
ul.addEventListener('click', handleDeleteAndCheck);
ul.addEventListener('click', editTask);
Here please change the statement with this in your handleDeleteAndCheck() method. It will remove the local storage at that time.
localStorage.removeItem('todo');