-
Notifications
You must be signed in to change notification settings - Fork 4
/
index.js
99 lines (90 loc) · 2.5 KB
/
index.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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
let taskInput = document.getElementById("taskInput");
let addBtn = document.getElementById("addTodo");
let taskContainer = document.getElementById("taskContainer");
let todos = [];
window.onload = () => {
todos = JSON.parse(localStorage.getItem("todos")) || [];
updateTodos();
};
let todo = {
id: "",
text: "",
done: false,
};
taskInput.onchange = (e) => {
todo.text = e.target.value;
};
function updateTodos() {
taskContainer.innerHTML = todos.map((val) => {
return `<div id="${val.id}" class="task-box">
<div class="content">
<input onchange="toggleDone(${val.id})" type="checkbox" ${
val.done ? "checked" : ""
} class="checkbox" />
<input
type="text"
class="task ${val.done ? "strikeout" : ""}"
value="${val.text}"
readonly
/>
</div>
<div class="actions">
<button onclick="editTodo(${val.id})" class="edit">Edit</button>
<button onclick="deleteTodo(${
val.id
})" class="delete">Delete</button>
</div>
</div>`;
});
localStorage.setItem("todos", JSON.stringify(todos));
}
addBtn.onclick = () => {
if (todo.text.trim().length) {
todo.id = Math.ceil(Math.random() * 100000);
todos.push(todo);
updateTodos();
todo = { id: "", text: "", done: false };
taskInput.value = "";
}
};
function editTodo(id) {
let ele = document.getElementById(id);
let inputEle = ele.children[0].children[1];
let btn = ele.children[1].children[0];
if (btn.innerHTML.toLowerCase() === "edit") {
inputEle.removeAttribute("readonly");
inputEle.focus();
btn.innerHTML = "save";
} else {
let idx = -1;
for (let index = 0; index < todos.length; index++) {
const tempTodo = todos[index];
if (tempTodo.id === id) {
idx = index;
break;
}
}
todos[idx].text = inputEle.value;
updateTodos();
btn.innerHTML = "edit";
}
}
function toggleDone(id) {
let inputEle = document.getElementById(id).children[0].children[1];
let checkbox = document.getElementById(id).children[0].children[0];
inputEle.classList.toggle("strikeout");
let idx = -1;
for (let index = 0; index < todos.length; index++) {
const tempTodo = todos[index];
if (tempTodo.id === id) {
idx = index;
break;
}
}
todos[idx].done = checkbox.checked;
updateTodos();
}
function deleteTodo(id) {
todos = todos.filter((val) => val.id !== id);
updateTodos();
}