-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
75 lines (66 loc) · 1.77 KB
/
app.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
document.addEventListener('DOMContentLoaded', function () {
loadTodos();
});
const serverURL = 'http://localhost:3000';
function loadTodos() {
fetch(`${serverURL}/todos`)
.then((response) => response.json())
.then((todos) => displayTodos(todos.slice(0, 10))); // Display only a few todos
}
function displayTodos(todos) {
const todoList = document.getElementById('todoList');
todos.forEach((todo) => {
const li = document.createElement('li');
li.innerHTML = `
<input type="checkbox" ${
todo.completed ? 'checked' : ''
} onclick="toggleTodo(${todo.id})">
<span>${todo.title}</span>
<button class="delete-btn" onclick="deleteTodo(${
todo.id
})">Delete</button>
`;
todoList.appendChild(li);
});
}
function addTodo() {
const newTodo = document.getElementById('newTodo').value;
if (newTodo.trim() !== '') {
fetch(`${serverURL}/todos`, {
method: 'POST',
body: JSON.stringify({
title: newTodo,
completed: false,
}),
headers: {
'Content-type': 'application/json; charset=UTF-8',
},
})
.then((response) => response.json())
.then(() => {
document.getElementById('newTodo').value = '';
refreshTodos();
});
}
}
function toggleTodo(id) {
fetch(`${serverURL}/todos/${id}`, {
method: 'PATCH',
body: JSON.stringify({
completed: true,
}),
headers: {
'Content-type': 'application/json; charset=UTF-8',
},
}).then(() => refreshTodos());
}
function deleteTodo(id) {
fetch(`${serverURL}/todos/${id}`, {
method: 'DELETE',
}).then(() => refreshTodos());
}
function refreshTodos() {
const todoList = document.getElementById('todoList');
todoList.innerHTML = '';
loadTodos();
}