79 lines
2.3 KiB
JavaScript
79 lines
2.3 KiB
JavaScript
document.addEventListener('DOMContentLoaded', () => {
|
|
const todoForm = document.getElementById('todo-form');
|
|
const todoInput = document.getElementById('todo-input');
|
|
const todoList = document.getElementById('todo-list');
|
|
const countAButton = document.getElementById('count-a-button');
|
|
const countAResult = document.getElementById('count-a-result');
|
|
|
|
todoForm.addEventListener('submit', (e) => {
|
|
e.preventDefault();
|
|
const task = todoInput.value;
|
|
if (task) {
|
|
addTodoToServer(task);
|
|
todoInput.value = '';
|
|
}
|
|
});
|
|
|
|
countAButton.addEventListener('click', () => {
|
|
countA();
|
|
});
|
|
|
|
function addTodoToServer(task) {
|
|
fetch('/todos', {
|
|
method: 'POST',
|
|
headers: {
|
|
'Content-Type': 'application/json'
|
|
},
|
|
body: JSON.stringify({ task })
|
|
})
|
|
.then(response => response.json())
|
|
.then(data => {
|
|
appendTodoToList(data.data.id, data.data.task);
|
|
});
|
|
}
|
|
|
|
function appendTodoToList(id, task) {
|
|
const todoItem = document.createElement('li');
|
|
todoItem.textContent = task;
|
|
todoItem.dataset.id = id;
|
|
const deleteButton = document.createElement('button');
|
|
deleteButton.textContent = 'Delete';
|
|
deleteButton.addEventListener('click', () => {
|
|
deleteTodoFromServer(id, todoItem);
|
|
});
|
|
todoItem.appendChild(deleteButton);
|
|
todoList.appendChild(todoItem);
|
|
}
|
|
|
|
function deleteTodoFromServer(id, todoItem) {
|
|
fetch(`/todos/${id}`, {
|
|
method: 'DELETE'
|
|
})
|
|
.then(response => response.json())
|
|
.then(() => {
|
|
todoList.removeChild(todoItem);
|
|
});
|
|
}
|
|
|
|
function fetchTodos() {
|
|
fetch('/todos')
|
|
.then(response => response.json())
|
|
.then(data => {
|
|
data.data.forEach(todo => {
|
|
appendTodoToList(todo.id, todo.task);
|
|
});
|
|
});
|
|
}
|
|
|
|
function countA() {
|
|
fetch('/count-a')
|
|
.then(response => response.json())
|
|
.then(data => {
|
|
countAResult.textContent = `Number of 'a' letters: ${data.count}`;
|
|
});
|
|
}
|
|
|
|
fetchTodos();
|
|
});
|
|
|