Skip to content

Commit 0a42e04

Browse files
committed
Finished wesbos#15
1 parent 86fff5e commit 0a42e04

File tree

1 file changed

+55
-1
lines changed

1 file changed

+55
-1
lines changed

15 - LocalStorage/index-START.html

Lines changed: 55 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,61 @@ <h2>LOCAL TAPAS</h2>
2828
<script>
2929
const addItems = document.querySelector('.add-items');
3030
const itemsList = document.querySelector('.plates');
31-
const items = [];
31+
const items = JSON.parse(localStorage.getItem('items')) || [];
32+
33+
function addItem(e) {
34+
e.preventDefault();
35+
36+
const text = (this.querySelector('[name="item"]')).value;
37+
38+
const item = {
39+
text,
40+
done: false
41+
};
42+
43+
items.push(item);
44+
populateList(items, itemsList);
45+
46+
// save items to local storage, but use 'stringify'
47+
// first bc local storage API only accepts strings
48+
localStorage.setItem('items', JSON.stringify(items));
49+
50+
this.reset();
51+
}
52+
53+
function populateList(plates = [], platesList) {
54+
platesList.innerHTML = plates.map((plate, i) => {
55+
return `<li>
56+
<input type="checkbox" data-index="${i}" id="item-${i}" ${plate.done ? 'checked' : ''} />
57+
<label for="item-${i}">${plate.text}</label>
58+
</li>`;
59+
}).join('');
60+
}
61+
62+
function toggleDone(e) {
63+
// only perform action on checkboxes
64+
if (!e.target.matches('input')) {
65+
return;
66+
}
67+
68+
const el = e.target;
69+
const index = el.dataset.index;
70+
71+
items[index].done = !items[index].done;
72+
localStorage.setItem('items', JSON.stringify(items));
73+
populateList(items, itemsList);
74+
75+
console.log(el.dataset.index);
76+
}
77+
78+
addItems.addEventListener('submit', addItem);
79+
itemsList.addEventListener('click', toggleDone);
80+
81+
populateList(items, itemsList);
82+
83+
// const checkboxes = document.querySelectorAll('.checkbox');
84+
// checkboxes.forEach(input => input.addEventListener('click', () => alert('Hi guys!')));
85+
3286

3387
</script>
3488

0 commit comments

Comments
 (0)