-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtodo.js
81 lines (68 loc) · 2.27 KB
/
todo.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
function Todo() {
var that = this;
this.init = function() {
document.getElementById('add').addEventListener('click', todo.add);
this.show();
}
this.get_todos = function() {
var todos = [];
var todos_str = localStorage.getItem('todo');
if (todos_str !== null) {
todos = JSON.parse(todos_str);
}
return todos;
};
this.add = function() {
var task = document.getElementById('task').value;
if (!task) {
return false;
}
var todos = that.get_todos();
todos.push(task);
localStorage.setItem('todo', JSON.stringify(todos));
document.getElementById('task').value = '';
that.show();
};
this.remove = function() {
event.stopPropagation();
var sure = confirm('Are you sure to remove?');
if (!sure) {
return false;
}
var id = this.parentElement.getAttribute('id');
var todos = that.get_todos();
todos.splice(id, 1);
localStorage.setItem('todo', JSON.stringify(todos));
that.show();
};
this.edit = function() {
var id = this.getAttribute('id');
var todos = that.get_todos();
var newVal = prompt('Set new value:', todos[id]);
if (!newVal) {
return false;
}
todos[id] = newVal;
localStorage.setItem('todo', JSON.stringify(todos));
that.show();
};
this.show = function() {
var todos = this.get_todos();
var html = '<ol>';
for(var i=0; i<todos.length; i++) {
html += '<li id="' + i + '" class="edit clearfix"><button class="remove btn btn-danger"><span class="glyphicon glyphicon-trash"></span></button>' +todos[i] + '</li>';
};
html += '</ol>';
document.getElementById('todos').innerHTML = html;
var buttons = document.getElementsByClassName('remove');
for (var i=0; i < buttons.length; i++) {
buttons[i].addEventListener('click', this.remove);
};
var buttons = document.getElementsByClassName('edit');
for (var i=0; i < buttons.length; i++) {
buttons[i].addEventListener('click', this.edit);
};
};
}
var todo = new Todo();
todo.init();