@@ -28,8 +28,50 @@ <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+ const text = ( this . querySelector ( '[name=item]' ) ) . value ;
36+ const item = {
37+ text,
38+ done : false
39+ }
3240
41+ items . push ( item ) ;
42+ populateList ( items , itemsList ) ;
43+ localStorage . setItem ( 'items' , JSON . stringify ( items ) ) ;
44+ this . reset ( ) ; // form elements have a reset function
45+ }
46+
47+ function populateList ( plates = [ ] , platesList ) {
48+ platesList . innerHTML = plates . map ( ( plate , index ) => {
49+ return `
50+ <li>
51+ <input
52+ type="checkbox"
53+ data-index=${ index }
54+ id="item${ index } "
55+ ${ plate . done ? 'checked' : '' }
56+ />
57+ <label for="item${ index } ">${ plate . text } </label>
58+ </li>
59+ `
60+ } ) . join ( '' ) . toString ( ) ;
61+ }
62+
63+ function toggleDone ( e ) {
64+ if ( ! e . target . matches ( 'input' ) ) return ;
65+ const el = e . target ;
66+ const index = el . dataset . index ;
67+ items [ index ] . done = ! items [ index ] . done ;
68+ localStorage . setItem ( 'items' , JSON . stringify ( items ) ) ;
69+ populateList ( items , itemsList ) ;
70+ }
71+
72+ addItems . addEventListener ( 'submit' , addItem ) ;
73+ itemsList . addEventListener ( 'click' , toggleDone ) ;
74+ populateList ( items , itemsList ) ;
3375</ script >
3476
3577
0 commit comments