Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // 03. Todo List
- // Exam Preparation I
- // https://judge.softuni.org/Contests/Practice/Index/3878#2
- function attachEvents() {
- let baseUrl = `http://localhost:3030/jsonstore/tasks/`;
- const titleElement = document.getElementById('title')
- const addBtnElement = document.getElementById('add-button')
- const loadBtnElement = document.getElementById('load-button')
- const toDoListElement = document.getElementById('todo-list')
- addBtnElement.addEventListener('click', addTask);
- loadBtnElement.addEventListener('click', loadAll);
- function addTask(e) {
- e.preventDefault();
- if (titleElement.value === '') {
- return;
- }
- const headers = { method: 'POST', body: JSON.stringify({ name: titleElement.value }) };
- fetch(baseUrl, headers).then(() => loadAll(e));
- titleElement.value = '';
- }
- function loadAll(e) {
- e?.preventDefault();
- toDoListElement.innerHTML = '';
- fetch(baseUrl)
- .then(res => res.json())
- .then(data => {
- for (let row in data) {
- let task = data[row]['name'];
- let id = data[row]['_id'];
- let newLi = document.createElement('li');
- newLi.id = id;
- let span = document.createElement('span');
- span.textContent = task;
- newLi.appendChild(span);
- let removeBtn = document.createElement('button');
- removeBtn.textContent = 'Remove';
- removeBtn.addEventListener('click', removeTask);
- newLi.appendChild(removeBtn);
- let editBtn = document.createElement('button');
- editBtn.textContent = 'Edit';
- editBtn.addEventListener('click', editTask);
- newLi.appendChild(editBtn);
- toDoListElement.appendChild(newLi);
- }
- })
- }
- function removeTask(e) {
- let id = e.target.parentNode.id;
- let delUrl = baseUrl + `${id}`;
- const headers = { method: 'DELETE', };
- fetch(delUrl, headers).then(() => loadAll());
- }
- function editTask(e) {
- let currentLi = e.target.parentNode
- let task = e.target.parentNode.children[0].textContent;
- currentLi.innerHTML = '';
- let input = document.createElement('input');
- input.value = task;
- currentLi.appendChild(input);
- let removeBtn = document.createElement('button');
- removeBtn.textContent = 'Remove';
- removeBtn.addEventListener('click', removeTask);
- currentLi.appendChild(removeBtn);
- let editBtn = document.createElement('button');
- editBtn.textContent = 'Submit';
- editBtn.addEventListener('click', submitHandle);
- currentLi.appendChild(editBtn);
- }
- function submitHandle(e) {
- console.log(e.target.parentNode.id)
- let editedTask = e.target.parentNode.children[0].value
- console.log(editedTask)
- let id = e.target.parentNode.id;
- let patchUrl = baseUrl + `${id}`;
- const headers = { method: 'PATCH', body: JSON.stringify({ name: editedTask }) };
- fetch(patchUrl, headers).then(() => loadAll());
- }
- }
- attachEvents();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement