-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathscript.js
More file actions
75 lines (63 loc) · 2.45 KB
/
script.js
File metadata and controls
75 lines (63 loc) · 2.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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
let todos = [];
function addTodo() {
const todoInput = document.getElementById("todoInput");
const todoText = todoInput.value.trim();
if (todoText === "") {
alert("Masukkan tugas terlebih dahulu!");
return;
}
todos.push({ text: todoText, isEditing: false });
todoInput.value = ""; // Clear input after adding
renderTodoList(); // Render the updated list
}
function renderTodoList() {
const todoList = document.getElementById("todoList");
todoList.innerHTML = ""; // Clear the list before rendering
todos.forEach((todo, index) => {
const li = document.createElement("li");
if (todo.isEditing) {
const input = document.createElement("input");
input.type = "text";
input.value = todo.text;
input.onblur = () => saveEdit(index, input.value);
input.onkeypress = (e) => {
if (e.key === 'Enter') {
saveEdit(index, input.value);
}
};
li.appendChild(input);
input.focus(); // Focus on the input for editing
} else {
const span = document.createElement("span");
span.textContent = todo.text;
li.appendChild(span);
}
const editButton = document.createElement("button");
editButton.textContent = todo.isEditing ? "Simpan" : "Edit";
editButton.onclick = () => editTodo(index);
li.appendChild(editButton);
const deleteButton = document.createElement("button");
deleteButton.textContent = "Hapus";
deleteButton.className = "delete";
deleteButton.onclick = () => deleteTodo(index);
li.appendChild(deleteButton);
todoList.appendChild(li); // Append the list item to the todo list
});
}
function editTodo(index) {
todos[index].isEditing = !todos[index].isEditing; // Toggle editing state
renderTodoList(); // Re-render the list
}
function saveEdit(index, newText) {
if (newText.trim() === "") {
alert("Teks tidak boleh kosong!"); // Prevent empty task
return;
}
todos[index].text = newText; // Update todo text
todos[index].isEditing = false; // Exit editing mode
renderTodoList(); // Re-render the list
}
function deleteTodo(index) {
todos.splice(index, 1); // Remove the todo from the array
renderTodoList(); // Re-render the list
}