장바구니 꾸미기

기여·2024년 8월 2일
0

소소한 개발팁

목록 보기
66/103

기존의 테이블도 좋았지만 여러가지 레이아웃 잡는 걸 경험해보고 싶기도 하고,
테이블로 유지하면 관리자 페이지와 비슷해 보여서 바꾸기로 했다.
이에 따라 연산에 관한 js도 변경되었다..!

(부분 선택/삭제 기능은 곧 개발 예정. 이번 포스팅은 오직 꾸미기에 대한 이야기 🤍)

html:

<section>
<br>
<div align="center">

<h1 th:text="'cart (' + ${lisize} + '건)'"></h1>

<form action="/cart/orderForm" method="post">

	<input type="hidden" name="uid" value="${session.username}">
	
	<div style="width: 800px; display: flex; flex-direction: column; align-items: center;">	 <!-- mediaList -->	
		<div style="width: 100%; display: flex; justify-content: flex-end; margin-bottom: 10px;"> <!-- totalPay & 주문버튼-->
		
			<input type="hidden" name="totalPay" id="totalPayInput" th:value="${totalPay}"><!-- totalPay값 입력 받을 영역 -->    
		    <span id="totalPayText"></span><!-- totalPay값, 즉 예상결제액 표시할 영역 -->
		    
		    &emsp;
		    <input type="submit" value="주문하기" class=button>
		    	
		</div>	
	
		<div th:each="m : ${li}" class="mediaObject" style="width: 800px; margin: 15px; 
		display: flex; flex-wrap: wrap; justify-content: left; background-color: #f4f4f4; 
		border-radius: 5px; box-shadow: 0 3px 5px #96a9fe, 0 2px 4px #96a9fe;"><!-- mediaObject -->
		
			<!-- 			1 -->
				<div style="margin-left: 10px;">
					<input type="checkbox" name="ckbox">
				</div>
				
				<div style="margin-left: 10px;">
					<a th:href="@{/prd/viewPrd(product_code=${m.product_code})}" target="_blank">
			            <img th:src="@{/img/}+${m.pimgStr}" width="150" />
			        </a>
				 </div>			
			<!-- 			1 끝 -->			
			
			<!-- 			2 -->
				<div style="text-align: left;">
					<div>
						 <a th:href="@{/prd/viewPrd(product_code=${m.product_code})}" 
				        th:text="${m.pname}" target="_blank">
				        </a>
					</div>
					
					<!-- 	수직 정렬 위해 span 대신 div 씀. span 쓰면서 수직은 유지하려면 각각 div으로 감싸기 -->
					<div>						
			        <input type="hidden" name="pprice" th:value="${m.pprice}">	
			        <span th:text="'판매가: ' + ${m.fmtPprice} + '원'"></span>
		        	</div>			
		        	            			            
			        <div>
			        <input type="hidden" name="pdelifee" th:value="${m.pdelifee}">
			        <span th:text="${m.pdelifee == 0 ? '무료배송❗' : '배송비: ' + m.fmtPdelifee + '원'}"></span>
			        </div>
		            <!-- 	수직 정렬 위해 span 대신 div 씀 -->
				</div>				
			<!-- 			2 끝 -->			
			
			<!-- 			3 -->
				<div style="margin-left: auto; margin-right: 10px; display: flex; flex-direction: column; text-align: right;">
					<div>
					주문수량: 
						<input type="number" name="pquantity" class="quantity-input" 
						th:value="${m.pquantity}" th:text="' / '+${m.pstock}" min="1" th:max="${m.pstock}">
						<!-- class="quantity-input" 통해 입력된 주문량을 js에 전달 -->
						
					</div>
				</div>
				
				<div style="margin-left: auto; margin-right: 10px; display: flex; flex-direction: column; text-align: right;">
				    
					<span class="item-total" th:text="'소계: ' + (${m.pprice * m.pquantity + m.pdelifee}) + '원'">소계</span>					

				</div>
				
				<div style="margin-left: auto; margin-right: 10px; display: flex; flex-direction: column; text-align: right;">					
						<a th:href="@{/cart/delCart(cartid=${m.cartid})}" >✖️</a>
				</div>
			<!-- 			3 끝 -->
			
		</div> <!-- mediaObject 끝 -->
	</div> <!-- mediaList 끝 -->

</form>
</div>
<br>
</section> 

js:

<script>
    document.addEventListener('DOMContentLoaded', function() {
        const quantityInputs = document.querySelectorAll('.quantity-input');
        const totalPayInput = document.getElementById('totalPayInput');
        const totalPayText = document.getElementById('totalPayText');
                
        // 천 단위에 콤마 찍기
        function formatNumber(number) {
            return number.toLocaleString();
        }
        
        // 계산하기
        function updateTotals() {
            let totalPay = 0;
            quantityInputs.forEach(input => {
                const mediaObject = input.closest('.mediaObject');
                const price = parseFloat(mediaObject.querySelector('input[name="pprice"]').value);
                const quantity = parseInt(input.value, 10);
                const deliveryFee = parseFloat(mediaObject.querySelector('input[name="pdelifee"]').value);
                const itemTotal = (price * quantity) + deliveryFee;                
                
                console.log('price: ', price);
                console.log('quantity: ', quantity);
                console.log('deliveryFee: ', deliveryFee);
                console.log('itemTotal: ', itemTotal);
                
                // 소계 업데이트
                const totalSpan = mediaObject.querySelector('.item-total');
				totalSpan.textContent = '소계: ' + formatNumber(itemTotal) + '원';			
                
                totalPay += itemTotal;
            });
            totalPayInput.value = totalPay;
            totalPayText.innerHTML = '예상결제액: <strong>' + formatNumber(totalPay) + '원</strong>';
        }
        
		// 수량 변경 시 계산 업데이트
        quantityInputs.forEach(input => {
            input.addEventListener('input', updateTotals);
        });

        updateTotals(); // 초기 계산
    });
</script>
profile
기기 좋아하는 여자

0개의 댓글