-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.js
79 lines (71 loc) · 2.01 KB
/
script.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
76
77
78
79
const inputToDo = document.querySelector("#input-to-do");
const btnToDo = document.querySelector("#add-to-do-btn");
const ulToDo = document.querySelector("#to-do-list");
const urlToDoAPI = "http://localhost:4730/todos";
const btnDeleteDone = document.querySelector("#delete-done-to-do");
let todos = [];
function getRequestAPI() {
fetch(urlToDoAPI)
.then((request) => request.json())
.then((toDosFromAPI) => {
todos = toDosFromAPI;
renderState();
});
}
getRequestAPI();
function renderState() {
todos.forEach((todo) => {
const newLi = document.createElement("li");
const checkbox = document.createElement("input");
const toDoDescription = todo.description;
newLi.innerText = toDoDescription;
checkbox.type = "checkbox";
checkbox.checked = todo.done;
checkbox.value = toDoDescription;
checkbox.id = todo.id;
newLi.appendChild(checkbox);
ulToDo.appendChild(newLi);
});
}
btnToDo.addEventListener("click", () => {
const newToDoDescription = inputToDo.value;
const newTodo = {
description: newToDoDescription,
done: false,
};
fetch(urlToDoAPI, {
method: "POST",
headers: { "content-Type": "application/json" },
body: JSON.stringify(newTodo),
})
.then((response) => response.json())
.then((backendState) => {});
});
ulToDo.addEventListener("change", (e) => {
e.checked = true;
const updatedToDo = {
id: e.target.id,
description: e.target.value,
done: true,
};
const urlIdToDoAPI = urlToDoAPI + "/" + e.target.id;
fetch(urlIdToDoAPI, {
method: "PUT",
headers: { "content-Type": "application/json" },
body: JSON.stringify(updatedToDo),
})
.then((response) => response.json())
.then((backendState) => {});
});
btnDeleteDone.addEventListener("click", () => {
getRequestAPI();
todos.forEach((todo) => {
if (todo.done === true) {
fetch(urlToDoAPI + "/" + todo.id, {
method: "DELETE",
})
.then((response) => response.json())
.then((backendState) => {});
}
});
});