Repository navigation
Expand file tree
/
Copy pathscript.js
More file actions
87 lines (69 loc) · 2.31 KB
/
Copy pathscript.js
File metadata and controls
87 lines (69 loc) · 2.31 KB
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
80
81
82
83
84
85
86
87
function handleTaskSubmission(event) {
event.preventDefault(); // Prevent the form from refreshing
// Get the task input value
let taskInputValue = document.getElementById("taskInput").value;
if (taskInputValue.length > 20) {
alert("Task is too long. Please limit it to 20 characters.");
} else {
addTaskToBackend(taskInputValue);
// Clear the input field after submission
document.getElementById("taskInput").value = "";
}
}
// Step 2: Attach the event listener to the form
document
.getElementById("taskForm")
.addEventListener("submit", handleTaskSubmission);
window.addEventListener("DOMContentLoaded", fetchTasks);
function fetchTasks() {
fetch("https://biztech-workshop.onrender.com/tasks")
.then((response) => response.json())
.then((tasks) => {
const taskList = document.getElementById("taskList");
taskList.innerHTML = "";
for (let i = 0; i < tasks.length; i++) {
const newTask = document.createElement("li");
newTask.textContent = tasks[i].task;
const deleteButton = document.createElement("button");
deleteButton.textContent = "Delete";
deleteButton.addEventListener("click", function () {
deleteTaskFromBackend(tasks[i].id, newTask);
});
newTask.appendChild(deleteButton);
taskList.appendChild(newTask);
}
});
}
function addTaskToBackend(task) {
fetch("https://biztech-workshop.onrender.com/tasks", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({ task })
})
.then((response) => response.json())
.then((newTask) => {
console.log(newTask);
addTaskToList(newTask);
});
}
function addTaskToList(task) {
let taskList = document.getElementById("taskList");
let newTask = document.createElement("li");
newTask.textContent = task.task;
const deleteButton = document.createElement("button");
deleteButton.textContent = "Delete";
deleteButton.addEventListener("click", function () {
deleteTaskFromBackend(task.id, newTask);
});
newTask.appendChild(deleteButton);
taskList.appendChild(newTask);
}
function deleteTaskFromBackend(taskId, taskElement) {
fetch(`https://biztech-workshop.onrender.com/tasks/${taskId}`, {
method: "DELETE"
}).then(() => {
taskElement.remove();
});
}