This is the js code
JavaScript
x
32
32
1
let form = document.getElementById('todoForm');
2
let input = document.getElementById('todoInput');
3
let btn = document.getElementById('btn');
4
let todos = [];
5
6
7
const loadTodos = () => {
8
let parent = document.getElementById('todoList');
9
todos.forEach(todo => {
10
let newLi = document.createElement('li');
11
newLi.innerHTML = `<li>${todo.text}</li>`
12
parent.appendChild(newLi);
13
})
14
}
15
16
btn.addEventListener('click', (e) => {
17
e.preventDefault();
18
let text = input.value;
19
let todo = {
20
id: todos.length + 1,
21
text: text,
22
complete: false,
23
}
24
todos.push(todo);
25
loadTodos();
26
})
27
28
29
window.onload = () => {
30
loadTodos();
31
}
32
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
JavaScript
1
39
39
1
let form = document.getElementById('todoForm');
2
let input = document.getElementById('todoInput');
3
let btn = document.getElementById('btn');
4
let todos = [];
5
6
7
const loadTodos = () => {
8
let parent = document.getElementById('todoList');
9
todos.forEach(todo => {
10
let newLi = document.createElement('li');
11
newLi.innerHTML = `<li>${todo.text}</li>`
12
parent.appendChild(newLi);
13
})
14
}
15
16
const renderNewToDo = (todo) => {
17
let parent = document.getElementById('todoList');
18
let newLi = document.createElement('li');
19
newLi.innerHTML = `<li>${todo.text}</li>`
20
parent.appendChild(newLi);
21
}
22
23
btn.addEventListener('click', (e) => {
24
e.preventDefault();
25
let text = input.value;
26
let todo = {
27
id: todos.length + 1,
28
text: text,
29
complete: false,
30
}
31
todos.push(todo);
32
renderNewToDo(todo);
33
})
34
35
36
window.onload = () => {
37
loadTodos();
38
}
39