1- import { cart , removeFromCart , calculateCartQuantity } from '../data/cart.js'
1+ import { cart , removeFromCart , calculateCartQuantity , updateQuantityLabel } from '../data/cart.js'
22import { products } from '../data/products.js'
33import { formatCurrency } from './utils/price.js' ;
44
@@ -38,13 +38,16 @@ cart.forEach((cartItem) => {
3838 </div>
3939 <div class="product-quantity">
4040 <span>
41- Quantity: <span class="quantity-label">${ cartItem . quantity } </span>
41+ Quantity: <span class="quantity-label js-quantity-label-${ matchingProduct . id } ">
42+ ${ cartItem . quantity } </span>
4243 </span>
4344 <span class="update-quantity-link link-primary js-link-primary js-update-button" data-item-id="${ matchingProduct . id } ">
4445 Update
4546 </span>
46- <input class="input-quantity">
47- <span class="save-quantity link-primary"> Save </span>
47+ <input class="input-quantity js-input-quantity-${ matchingProduct . id } "
48+ type="number" min="1">
49+ <span class="save-quantity link-primary js-save-link" data-item-id="${ matchingProduct . id } ">
50+ Save </span>
4851 <span class="delete-quantity-link link-primary js-delete-button" data-item-id="${ matchingProduct . id } ">
4952 Delete
5053 </span>
@@ -130,8 +133,42 @@ document.querySelectorAll(`.js-update-button`)
130133 const { itemId} = button . dataset ;
131134
132135 const container = document . querySelector ( `.js-cart-item-${ itemId } ` )
133- . classList . add ( 'is-editing-quantity' )
134136
137+ container . classList . add ( 'is-editing-quantity' ) ;
138+
139+ const input = document . querySelector ( `.js-input-quantity-${ itemId } ` )
140+ input . select ( ) ;
141+ input . addEventListener ( 'keydown' , ( event ) => {
142+ if ( event . key === 'Enter' ) {
143+ saveUpdatedQuantity ( itemId ) ;
144+ }
145+ } )
146+ } )
147+ } ) ;
148+
149+
150+ function saveUpdatedQuantity ( itemId ) {
151+ const container = document . querySelector ( `.js-cart-item-${ itemId } ` ) ;
152+ container . classList . remove ( 'is-editing-quantity' ) ;
153+
154+
155+ const quantityInput = document . querySelector ( `.js-input-quantity-${ itemId } ` )
156+
157+ const newQuantity = Number ( quantityInput . value ) ;
158+
159+ updateQuantityLabel ( newQuantity , itemId ) ;
160+ updateCartQunatity ( ) ;
161+
162+ quantityInput . value = null ;
163+ } ;
164+
165+
166+ document . querySelectorAll ( '.js-save-link' )
167+ . forEach ( ( link ) => {
168+ const { itemId} = link . dataset ;
169+ link . addEventListener ( 'click' , ( ) => {
170+
171+ saveUpdatedQuantity ( itemId ) ;
135172
136173 } )
137- } )
174+ } ) ;
0 commit comments