-
Notifications
You must be signed in to change notification settings - Fork 0
/
todo.html
131 lines (112 loc) · 3.15 KB
/
todo.html
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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
<html>
<head>
<title> My Todo App </title>
</head>
<body>
<input id="todo-title", type="text" />
<input id = "date-picker", type = "date" />
<button onclick= "addTodo()"> Add Todo </button>
<div id="todo-list"></div>
<script>
// Model
// If localstorge has a todos array, we will continue use that array
// Else we use the default array below
let todos;
// Retrieve localStorage
const savedTodos = JSON.parse(localStorage.getItem('todos'));
// Check if it is an array
if (Array.isArray(savedTodos))
{ todos = savedTodos; }
else
{
todos =
[
{
title: 'Get groceries',
dueDate: '2021-10-03',
id: 'id1'
},
{
title: 'Wash car',
dueDate: '2021-10-04',
id: 'id2'
},
{
title: 'Make dinner',
dueDate: '2021-10-05',
id: 'id3'
}
];
}
render();
// Create a to do
function createTodo(title, dueDate)
{
const id = ' ' + new Date().getTime();
todos.push(
{
title: title,
dueDate: dueDate,
id: id
}
);
saveTodos();
}
// Delete a to do
function removeTodo(idToDelete)
{
todos = todos.filter(function (todo)
{
// If the id of this todo matches idToDelete, return false => to delete
// For eveything else, return true => to keep
if (todo.id === idToDelete) { return false; }
else { return true; }
});
saveTodos();
}
function saveTodos()
{
localStorage.setItem('todos',JSON.stringify(todos));
}
// Controller
function addTodo()
{
// Respond to the "button click" event
const textbox = document.getElementById('todo-title');
const title = textbox.value;
const datePicker = document.getElementById('date-picker');
const dueDate = datePicker.value;
createTodo(title, dueDate);
render();
}
function deleteTodo(event)
{
// remove item in the todo list
const deleteButton = event.target;
const idToDelete = deleteButton.id;
removeTodo(idToDelete);
render();
}
// View
function render()
{
// reset our list to be empty
document.getElementById('todo-list').innerHTML = ' ';
// re-render
todos.forEach(function(todo)
{
const element = document.createElement('div');
element.innerText = todo.title + ' ' + todo.dueDate;
const deleteButton = document.createElement('button');
deleteButton.innerText = 'Delete';
deleteButton.style ='margin-left: 12px';
deleteButton.onclick = deleteTodo;
deleteButton.id = todo.id;
element.appendChild(deleteButton);
const todoList = document.getElementById('todo-list')
todoList.appendChild(element);
});
}
</script>
</body>
</html>