This is the js code
let form = document.getElementById('todoForm'); let input = document.getElementById('todoInput'); let btn = document.getElementById('btn'); let todos = []; const loadTodos = () => { let parent = document.getElementById('todoList'); todos.forEach(todo => { let newLi = document.createElement('li'); newLi.innerHTML = `<li>${todo.text}</li>` parent.appendChild(newLi); }) } btn.addEventListener('click', (e) => { e.preventDefault(); let text = input.value; let todo = { id: todos.length + 1, text: text, complete: false, } todos.push(todo); loadTodos(); }) window.onload = () => { loadTodos(); }
When I add a todo for the first time its ok, but the seconed time will print the first todo again include the seconed.
example:
- first todo 2.first todo 3.seconed todo
Advertisement
Answer
You should make another function to handle single todo added, below is your updated code
let form = document.getElementById('todoForm'); let input = document.getElementById('todoInput'); let btn = document.getElementById('btn'); let todos = []; const loadTodos = () => { let parent = document.getElementById('todoList'); todos.forEach(todo => { let newLi = document.createElement('li'); newLi.innerHTML = `<li>${todo.text}</li>` parent.appendChild(newLi); }) } const renderNewToDo = (todo) => { let parent = document.getElementById('todoList'); let newLi = document.createElement('li'); newLi.innerHTML = `<li>${todo.text}</li>` parent.appendChild(newLi); } btn.addEventListener('click', (e) => { e.preventDefault(); let text = input.value; let todo = { id: todos.length + 1, text: text, complete: false, } todos.push(todo); renderNewToDo(todo); }) window.onload = () => { loadTodos(); }