-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path15.js
46 lines (43 loc) · 1.5 KB
/
15.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
function storeItLocally() {
const addItems = document.querySelector(".add-items");
const itemsList = document.querySelector(".plates");
const items = JSON.parse(localStorage.getItem("items")) || [];
function addItem(e) {
e.preventDefault();
const itemName = this.querySelector("[name=item]").value;
const item = {
itemName,
done: false,
};
items.push(item);
populateList(items, itemsList);
localStorage.setItem("items", JSON.stringify(items));
this.reset();
}
function populateList(plates = [], platesList) {
platesList.innerHTML = plates
.map((plate, i) => {
return `
<li>
<input type="checkbox" data-index=${i} id="item${i}" ${
plate.done ? "checked" : ""
}/>
<label for="item${i}">${plate.itemName}</label>
</li>
`;
})
.join("");
}
function toggleDone(e) {
if (!e.target.matches("input")) return;
const element = e.target;
const index = element.dataset.index;
items[index].done = !items[index].done;
localStorage.setItem("items", JSON.stringify(items));
populateList(items, itemsList);
}
addItems.addEventListener("submit", addItem);
itemsList.addEventListener("click", toggleDone);
populateList(items, itemsList);
}
window.addEventListener("DOMContentLoaded", storeItLocally);