@@ -28,7 +28,61 @@ <h2>LOCAL TAPAS</h2>
28
28
< script >
29
29
const addItems = document . querySelector ( '.add-items' ) ;
30
30
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
+
32
86
33
87
</ script >
34
88
0 commit comments