게으른 완벽주의자의 개발자 도전기
[shop] 장바구니 구현하기1(체크박스, 총가격) 본문
1. html
<table class="table align-middle">
<colgroup>
<col width="5%">
<col width="5%">
<col width="15%">
<col width="30%">
<col width="15%">
<col width="15%">
<col width="15%">
</colgroup>
<thead>
<tr>
<td><input type="checkbox" id="checkAll"></td>
<td>No</td>
<td colspan="2">상품 정보</td>
<td>수량</td>
<td>가격</td>
<td>등록일</td>
</tr>
</thead>
<tbody>
<th:block th:each="cart, status : ${cartList}">
<tr>
<td><input type="checkbox" class="chk" th:value="${cart.cartCode}" th:data-item-code="${cart.itemList.itemCode}" checked></td>
<td>
<span th:text="${#lists.size(cartList) - status.index}"></span>
</td> <!-- 전체개수 - index -->
<td> <img th:src="|@{/image/}${cart.itemList.imgList[0].attachedName}|" width="100px" height="100px"></td>
<td>
[<span th:text="${cart.itemList.cateInfo.cateName}"></span>]
<span th:text="${cart.itemList.itemName}"></span>
</td>
<td>
<div class="input-group mb-3">
<input type="text" class="form-control amountInput" aria-describedby="button-addon2" th:value="${cart.cartAmount}" th:data-origin-amount="${cart.cartAmount}">
<button class="btn btn-outline-primary" type="submit" id="button-addon2" th:onclick="updateCnt(this);">변경</button>
</div>
</td>
<td>
[[${cart.itemList.itemPrice}]] * [[${cart.cartAmount}]]
<div class="totalPriceDiv" th:data-total-price ="${cart.totalPrice}">
[[${#numbers.formatCurrency(cart.totalPrice)}]]
</div>
</td>
<td th:text="${cart.regDate}"></td>
</tr>
</th:block>
</tbody>
</table>
2. js
//---------------- 스크립트 실행과 동시에 필요한 변수 생성 ---------------------//
제목줄 체크박스
const checkAll = document.querySelector('#checkAll');
제목줄 제외한 장바구니 체크박스
const chks = document.querySelectorAll('.chk');
전체선택, 전체해제 이벤트
checkAll.addEventListener('click',function(){
제목 줄 체크박스 체크여부
const isChecked = checkAll.checked; //true, false
장바구니 목록 모든 체크박스
const checkBoxes = document.querySelectorAll('.chk');
제목줄 체크박스가 체크되었다면
if(isChecked){
모든 체크박스에 체크 표시
for(const checkBox of checkBoxes){
checkBox.checked = true;
}
}
else{
모든 체크박스 체크 해제
for(const checkBox of checkBoxes){
checkBox.checked = false;
}
}
총 금액
setFinalPrice();
});
총 가격을 세팅하는 함수
function setFinalPrice(){
체크된 체크박스 선택
const checkedBoxes = document.querySelectorAll('.chk:checked');
let finalPrice = 0;
for(const checkedBox of checkedBoxes){
const totalPrice = parseInt(checkedBox.closest('tr').querySelector('.totalPriceDiv').dataset.totalPrice);
finalPrice = totalPrice + finalPrice;
}
document.querySelector('#finalPriceSpan').innerText = '₩' + finalPrice.toLocaleString();
}
장바구니 목록에 있는 체크박스 클릭 시 진행
for(const chk of chks){
chk.addEventListener('click',function(){
setFinalPrice();
});
}
'Spring Boot' 카테고리의 다른 글
[shop]장바구니 구현하기3 (선택 삭제, 선택 구매) (0) | 2022.10.23 |
---|---|
[shop] 장바구니 구현하기2(장바구니 리스트, 수량 변경) (0) | 2022.10.23 |
[shop]상세페이지 구매하기(단일 구매) 구현 (0) | 2022.10.23 |
[shop] 상품 상세페이지 화면 구현하기 (0) | 2022.10.23 |
[shop] 상품 상세페이지 장바구니 버튼 구현 (0) | 2022.10.23 |