forked from FirmanKurniawan/Javascript-Projects
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTodoList-Project.js
More file actions
59 lines (47 loc) · 1.45 KB
/
TodoList-Project.js
File metadata and controls
59 lines (47 loc) · 1.45 KB
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
//retrieve data from local storage
function get_todos(){
var todos = new Array;
var todos_str = localStorage.getItem('todo');
if(todos_str !== null){
todos = JSON.parse(todos_str);
}
return todos;
}
function add(){
var task = document.getElementById('task').value;
var todos = get_todos();
todos.push(task);
localStorage.setItem('todo', JSON.stringify(todos));
show();
clearDefault();
return false; //avoids any futher action with click event
}
//clear the task value from input box
function clearDefault(){
document.getElementById('task').value = '';
};
//remove tasks from the list
function remove(){
var id = this.getAttribute('id');//refers to current DOM element
var todos = get_todos();
todos.splice(id, 1);
localStorage.setItem('todo', JSON.stringify(todos));
show();
return false; //avoids further action with click event
}
function show(){
var todos = get_todos();
var html = '<ul>';
for(var i = 0; i < todos.length; i++){
html += '<li>' + todos[i] + '<button class="remove" id="' + i + '">Delete</button> </li>';
};
html += '</ul>';
console.log(html);
document.getElementById('todos').innerHTML = html;
var buttons = document.getElementsByClassName('remove');
for(var i=0; i < buttons.length; i++){
buttons[i].addEventListener('click', remove);
};
}
document.getElementById('add').addEventListener('click', add);
show();