forked from codepo8/simple-to-do
-
Notifications
You must be signed in to change notification settings - Fork 0
/
simple-to-do.js
60 lines (56 loc) · 1.48 KB
/
simple-to-do.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
const form = document.querySelector('form');
const list = document.querySelector('#tasks');
const task = document.querySelector('#task');
const updateList = () => {
window.localStorage.setItem(
'mytasks',
JSON.stringify(tasks)
);
let out = '';
for(t of Object.keys(tasks)) {
out += `
<li>
<label>
<input type="checkbox"
${tasks[t] === 'done' ? 'checked' : ''}
value="${t}"><span>${t}</span>
<button type="button" data-task="${t}">x</button>
</label>
</li>`;
}
list.innerHTML = out;
};
const addTask = e => {
if (task.value) {
let t = task.value.replace(/[^A-Z|0-9| ]+/ig, '');
if (t.value !== t) {
console.warn('cleaned up task value');
t.value = t;
}
console.info('Adding Task :' + t);
tasks[t] = 'active';
updateList();
task.value = '';
}
e.preventDefault();
};
const changeTask = e => {
let t = e.target;
if (t.dataset.task) {
delete tasks[t.dataset.task];
console.info(`Removed: ${t.dataset.task}`);
updateList();
e.preventDefault();
}
if (t.nodeName.toLowerCase() === 'input') {
tasks[t.value] = t.checked ? 'done' : 'active';
console.info(t.value + ': '+ tasks[t.value])
updateList();
e.preventDefault();
}
}
let tasks = window.localStorage.getItem('mytasks') ?
JSON.parse(window.localStorage.getItem('mytasks')) : {} ;
updateList(tasks)
list.addEventListener('click', changeTask);
form.addEventListener('submit', addTask);