hyeonga_code

reProject_11_장바구니 페이지 구현 본문

Project_WEATHERWEAR

reProject_11_장바구니 페이지 구현

hyeonga 2023. 12. 28. 05:59
반응형

 

 

 

reProject_10_사용자 상품 상세 페이지 구현

reProject_09_사용자 상품 리스트 페이지 구현 2023.12.23 - [Project] - reProject_08_회원 정보 찾기 기능 구현(아이디 찾기, 비밀번호 찾기) 2023-12-22 -- 회원 기능을 완벽하게 구현하지 않았으나 다음주 금요

hyeonga493.tistory.com


2023.12.26 - 2023.12.27

- 기존 프로젝트에서 작업한 table 태그 대신 div, ul 태그를 사용하여 테이블을 구성

- 현재 기능을 수행하기 위해 두 개의 상품을 임의로 박아둠

- 수량 변경시 Price 란의 가격, 하단의 총 상품금액에 자동으로 적용되게 함

 

-- 장바구니 페이지 구현

1. client_cart.jsp 작성

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>WEATHERWEAR</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="/w2/resources/util/util_js/util_checkbox.js"></script>
    <script src="/w2/resources/client/client_js/client_cart.js"></script>
    <link rel="stylesheet" href="/w2/resources/client/client_css/client_base_style.css">
    <link rel="stylesheet" href="/w2/resources/client/client_css/client_cart_style.css">
</head>
<body>
    <div class="container">
        <%@ include file="/WEB-INF/views/client/base/client_header.jspf" %>
        <div class="body">
                <div class="cartList">
                    <h2>CART</h2>
                    <div class="cart_table">
                        <ul class="cart_header">
                            <li class="cart_head no">
                                <input type="checkbox" id="checkAll" name="checkAll">
                                <label for="checkAll"></label>
                            </li>
                            <li class="cart_head con">PRODUCT</li>
                            <li class="cart_head count">COUNT</li>
                            <li class="cart_head price">PRICE</li>
                        </ul>
    <!-- 상품마다 반복 시작 -->
                        <ul class="cart_content checklist">
                            <li class="cart_con no">
                    <!-- value/id > proId -->                            
                                <input type="checkbox" name="checkbox" id="W2OT40044_checkbox" class="check" value="W2OT40044">
                    <!-- for > proId(id) -->                            
                                <label for="W2OT40044_checkbox"></label>
                            </li>
                            <li class="cart_con con">
                                <div class="product_info_div">
                                <section class="product_image_section">
            <!-- 상품상세로 이동 -->
                    <!-- 상품 이미지(imageDir / imageName) -->        
                                    <img class="product_image" src="https://hyeongabucket.s3.ap-northeast-2.amazonaws.com/product_image/2312040327pdjhdehtso_0.jpg" onclick="location.href='clientProductInfo.do?proId=W2OT40044'">
                                </section>
                                <section class="product_content_section">
                                    <span class="order_product_name">
            <!-- 상품상세로 이동 -->
                                        <a href="clientProductInfo.do?proId=W2OT40044" class="community_a">
                    <!-- 상품 이름 -->        
                                            GU컬리후리스집업베스트
                                        </a>
                                    </span>
                                    <span class="order_product_option">
                    <!-- 선택 색상/옵션 -->        
                                        오프화이트 / M
                                    </span>
                                </section>
                                </div>
                            </li>
                            <li class="cart_con count">
                    <!-- id > proId -->        
                                <div id="W2OT40044" class="cartValue">
                                    <button type="button" class="pro_btn" onclick="count(2,'W2OT40044')">-</button>
                                    <input class="pro_btn" name="W2OT40044" value="1">
                                    <button type="button" class="pro_btn" onclick="count(1,'W2OT40044')">+</button>
                    <!-- 상품 기본 가격 > value : 상품 기본 가격 -->
                                    <input type="hidden" name="W2OT40044_oriPrice" value="5000">
                                </div>
                            </li>
                            <li class="cart_con price">
                    <!-- id > proId + '_price' -->        
                                <div id="W2OT40044_price">
                    <!-- 상품가격*수량 합계 출력 -->
                                    <span id="W2OT40044_totalPrice" class="pro_totalPrice"></span>
                    <!-- 상품가격*수량 합계 -->
                                    <input type="hidden" name="W2OT40044_totalPrice">
                                </div>
                            </li>
                        </ul>
    <!-- 상품마다 반복 끝 -->
    <!-- 상품마다 반복 시작 -->
                        <ul class="cart_content checklist">
                            <li class="cart_con no">
                    <!-- value/id > proId -->                            
                                <input type="checkbox" name="checkbox" id="W2TS16128_checkbox" class="check" value="W2TS16128">
                    <!-- for > proId(id) -->                            
                                <label for="W2TS16128_checkbox"></label>
                            </li>
                            <li class="cart_con con">
                                <div class="product_info_div">
                                <section class="product_image_section">
            <!-- 상품상세로 이동 -->
                    <!-- 상품 이미지(imageDir / imageName) -->        
                                    <img class="product_image" src="https://hyeongabucket.s3.ap-northeast-2.amazonaws.com/product_image/2312032123zjlcvhonbn_0.jpg" onclick="location.href='clientProductInfo.do?proId=W2TS16128'">
                                </section>
                                <section class="product_content_section">
                                    <span class="order_product_name">
            <!-- 상품상세로 이동 -->
                                        <a href="clientProductInfo.do?proId=W2TS16128" class="community_a">
                    <!-- 상품 이름 -->        
                                        3D니트캐시미어크루넥스웨터(긴팔)
                                        </a>
                                    </span>
                                    <span class="order_product_option">
                    <!-- 선택 색상/옵션 -->        
                                        그레이 / M
                                    </span>
                                </section>
                                </div>
                            </li>
                            <li class="cart_con count">
                    <!-- id > proId -->        
                                <div id="W2TS16128" class="cartValue">
                                    <button type="button" class="pro_btn" onclick="count(2,'W2TS16128')">-</button>
                                    <input class="pro_btn" name="W2TS16128" value="1">
                                    <button type="button" class="pro_btn" onclick="count(1,'W2TS16128')">+</button>
                    <!-- 상품 기본 가격 > value : 상품 기본 가격 -->
                                    <input type="hidden" name="W2TS16128_oriPrice" value="27000">
                                </div>
                            </li>
                            <li class="cart_con price">
                    <!-- id > proId + '_price' -->        
                                <div id="W2TS16128_price">
                    <!-- 상품가격*수량 합계 출력 -->
                                    <span id="W2TS16128_totalPrice" class="pro_totalPrice"></span>
                    <!-- 상품가격*수량 합계 -->
                                    <input type="hidden" name="W2TS16128_totalPrice">
                                </div>
                            </li>
                        </ul>
    <!-- 상품마다 반복 끝 -->
    
    <!-- 삭제 버튼 -->
                        <div class="cart_btn_div delete_btn">
                            <input type="button" id="addWishList" class="cart_btn" value="관심상품으로 이동">
                            <input type="button" id="deleteSelected" class="cart_btn" value="선택 삭제" onclick="deleteSelect()">
                            <input type="button" id="deleteAll" class="cart_btn" value="전체 삭제" onclick="deleteAll()">
                        </div>
                    </div>
                    <div class="cart_table_option">
    <!-- 금액 -->
                        <div class="cart_total">
                            <ul class="cart_total_ul">
                                <li class="cart_total_li"><span>총 상품금액</span></li>
                                <li class="cart_total_li val">
                                    <span id="totalPrice"></span>
                                    <input type="hidden" name="totalPrice">
                                </li>
                            </ul>
                            <ul class="cart_total_ul buho">
                                <li class="cart_total_buho">+</li>
                            </ul>
                            <ul class="cart_total_ul">
                                <li class="cart_total_li"><span>총 배송비</span></li>
                                <li class="cart_total_li val">
                                    <span id="deliPrice"></span>
                                    <input type="hidden" name="deliPrice">
                                </li>
                            </ul>
                            <ul class="cart_total_ul buho">
                                <li class="cart_total_buho">=</li>
                            </ul>
                            <ul class="cart_total_ul">
                                <li class="cart_total_li"><span>결제 예정 금액</span></li>
                                <li class="cart_total_li val">
                                    <span id="endPrice"></span>
                                    <input type="hidden" name="endPrice">
                                </li>
                            </ul>
                        </div>
    <!-- 주문 버튼 -->
                        <div class="cart_btn_div order_btn">
                            <input type="button" id="orderSelected" class="cart_btn" value="선택 상품 주문">
                            <input type="button" id="orderAll" class="cart_btn" value="전체 상품 주문">
                        </div>
                    </div>
                </div>                
        </div>
        <%@ include file="/WEB-INF/views/client/base/client_footer.jspf" %>
    </div>
</body>
</html>

 

2. ClientGetController.java 수정

	/** 장바구니 */
	@RequestMapping("clientCart.do")
	public String cart() {
		System.out.println("1. [ Client Get Controller ] cart");
		
		return "client_cart";
	}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
package com.w2.client.controller;
 
import java.util.HashMap;
import java.util.List;
 
import javax.servlet.http.HttpSession;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
 
import com.w2.client.ClientService;
import com.w2.client.ClientVO;
import com.w2.client.product.ClientProductService;
 
@Controller
public class ClientGetController {
 
    @Autowired
    private ClientService clientService;
    
    @Autowired
    private ClientProductService productService;
    
    /** 사용자 메인페이지 */
    @RequestMapping("clientMain.do")
    public String main() {
        return "client_main";
    }
    
    /** 상품 리스트 페이지 */
    @RequestMapping("clientProductList.do")
    public String clientProductList(@RequestParam(value = "page", required = false)Integer page, 
                                @RequestParam(value="ordertype", required=falseString ordertype, 
                                @RequestParam(value="gubun", required=false)String gubun, Model model) {
        System.out.println("1. [ Client Get Controller ] productList");
        
        HashMap<String, Object> check = new HashMap<String, Object>();
        if(page == null || page == 0) {
            check.put("page"1);
        } else {
            check.put("page", (int)page);
        }
        
        check.put("table""product");
        check.put("ordertype", (String)ordertype);
        check.put("gubun", (String)gubun);
        
        
        List<HashMap<String, Object>> productList = productService.clientProductList(check, model);
        
        model.addAttribute("productList", productList);
        
        return "client_productList";
    }
    
    /** 상품 상세 페이지 */
    @RequestMapping("clientProductInfo.do")
    public String clientProductInfo(@RequestParam(value = "proId", required = false)String proId, Model model) {
        System.out.println("1. [ Client Post Controller ] clientProductInfo");
        
        model.addAttribute("product", productService.clientProductInfo(proId));
        
        return "client_productInfo";
    }
    
    /** 사용자 로그인 페이지 */
    @RequestMapping("clientLogin.do")
    public String login() {
        return "client_login";
    }
 
    /** 로그아웃 요청 */
    @RequestMapping("clientLogout.do")
    public String logout(HttpSession session) {
        if(session != null) {
            session.invalidate();
        }
        return "redirect:/clientMain.do";
    }
    
    /** 사용자 정보 찾기 페이지 */
    @RequestMapping("clientFindInfo.do")
    public String findInfo() {
        return "client_findInfo";
    }
 
    /** 회원가입 페이지 */
    @RequestMapping("clientSignup.do")
    public String signup() {
        return "client_signup";
    }
    
    /** 커뮤니티 페이지 */
    @RequestMapping("clientCommunity.do")
    public String community() {
        return "client_community";
    }
    
    /** 마이페이지 */
    @RequestMapping("clientMypage.do")
    public String mypage(HttpSession session, ClientVO client, Model model) {
        System.out.println("1. [ Client Get Controller ] myPage ");
        
        if(session!=null) {
            HashMap<String, Object> myinfo = clientService.clientSetMypage((String)session.getAttribute("session"));
            model.addAttribute("myinfo", myinfo);
        }
        
        return "client_mypage";
    }
    
    /** 장바구니 */
    @RequestMapping("clientCart.do")
    public String cart() {
        System.out.println("1. [ Client Get Controller ] cart");
        
        return "client_cart";
    }
}

 

 

3. client_cart.js 파일 작성

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
$(document).ready(function(){
    setPrice();
    
});
 
// 값 설정
function setPrice(){
    // 상품별 count li 태그 찾기
    const cartCounts = document.querySelectorAll(".cart_con.count");
    
    // input
    const totalPriceInput = document.querySelector("input[name='totalPrice']");
    const deliPriceInput = document.querySelector("input[name='deliPrice']");
    const endPriceInput = document.querySelector("input[name='endPrice']");
    
    //span
    const totalPriceSpan = document.querySelector("#totalPrice");
    const deliPriceSpan = document.querySelector("#deliPrice");
    const endPriceSpan = document.querySelector("#endPrice");
    
    let totalPriceVal = 0;
    let deliPriceVal = 3000;
    
    // 상품별
    cartCounts.forEach(cartId => {
        // div
        const cartValue = cartId.querySelector(".cartValue");
        
        // proId
        const proId = cartValue.id;
        
        // 수량
        const countInput = document.querySelector("input[name='" + proId + "']");
        
        // 기본 가격
        const oriPriceInput = document.querySelector("input[name='" + proId + "_oriPrice']");
        
        const priceDiv = document.querySelector("#" + proId + "_price");
        const pro_totalPriceSpan = priceDiv.querySelector("#" + proId + "_totalPrice");
        const pro_totalPriceInput = priceDiv.querySelector("input");
        
        // (기본가격 * 수량)
        let pro_totalPrice = countInput.value * oriPriceInput.value
        
        pro_totalPriceSpan.innerHTML = setFormat(pro_totalPrice);
        pro_totalPriceInput.value = pro_totalPrice;
 
        // 총 상품 금액
        totalPriceVal += pro_totalPrice;                
    });
    
    // 배송비 조건부 무료
    if(totalPriceVal > 50000){
        deliPriceVal = 0;
    }
 
    totalPriceInput.value = totalPriceVal;
    deliPriceInput.value = deliPriceVal;
    endPriceInput.value = totalPriceVal + deliPriceVal;
    
    totalPriceSpan.innerHTML = setFormat(totalPriceVal);
    deliPriceSpan.innerHTML = setFormat(deliPriceVal);
    endPriceSpan.innerHTML = setFormat(totalPriceVal + deliPriceVal);
}
 
// 수량 증가
function count(num, name) {
    const countInput = document.querySelector("input[name='" + name + "']");
    const pro_oriPriceInput = document.querySelector("input[name='" + name + "_oriPrice']");
    const pro_totalPriceInput = document.querySelector("input[name='" + name + "_totalPrice']");
    const pro_totalPriceSpan = document.querySelector("#" + name + "_totalPrice");
 
    let cnt = parseInt(countInput.value);
    let pro_oriPrice = parseInt(pro_oriPriceInput.value);
    let pro_totalPrice = parseInt(pro_totalPriceInput.value);
    
    if (num == 1) { // 수량 증가
        pro_totalPrice += pro_oriPrice;
        cnt++;
    } else if (num == 2){ // 수량 감소
        pro_totalPrice -= pro_oriPrice;
        cnt--;
    }
    
    if(cnt < 1){
        alert("수량은 1개 이상이어야 합니다.");
        cnt = 1;
        pro_totalPrice = pro_oriPrice;
    }
    
    countInput.value = cnt;
    pro_totalPriceInput.value = pro_totalPrice;
    pro_totalPriceSpan.innerHTML = setFormat(pro_totalPrice);
    
    setPrice();
}
 
// 숫자 표기
function setFormat(num){
    let result = num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    return result;
}

 

 

4. client_cart_style.css 파일 작성

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
@charset "UTF-8";
 
/* 장바구니 div */
.cartList{
    width: 100%;
    display: flex;
    flex-direction: column;
    align-items: center;
}
 
/* 장바구니 목록 */
    .cart_table {
        width: 90%;
        height: auto;
        min-height: 450px;
        display: flex;
        flex-direction: column;
        align-items: center;
    }
    
    .cart_table > ul {
        width: 100%;
        list-style-type: none;
        display: flex;
        flex-direction: row;
        align-items: inherit;
        padding: 0px;
        margin: 0;
        border-bottom : 1px solid #dfdfdf;
    }
 
/* 테이블 규격 */
    .cart_header {
        height: 40px;
    }
    
    .cart_head {
        display: inline-block;
        margin: 5px auto;
        text-align: center;
    }
    
    .cart_content {
        height: 180px;
        min-height: 150px; 
    }
    
    .cart_con {
        height: 150px;
        display: flex;
        flex-direction: row;
        justify-content: center;
        align-items: center;
    }
    
    .product_image {
        min-width: 150px;
        min-height: 150px;
        max-width: 170px;
        max-height: 170px;
        width: 70%;
        height: auto;
    }
    
    .no { width: 5%; text-align: center; }
    .con { width: 50%; }
    .count { width: 25%; min-width: 150px; text-align: center; }
    .product { width: 17%; text-align: center; }
    
    .price { 
        width: 20%; 
        text-align: center; 
        display: flex;
        flex-direction: column;
        justify-content: center;
    }
 
.product_info_div {
    width: 100%;
    display: flex;
}
 
/* 상품 정보 */
    .content { 
        width: 33%;
        max-width: 33%;
        display: flex;
        justify-content: center;
        flex-direction: column;
        margin-left: 20px;
    }
    
    .product_content_section {
        width: 100%;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis; 
        display: flex;
        justify-content: center;
        flex-direction: column;
        margin-left: 20px;
    }
    
    .order_product_name {
        width: 100%;
        height: 30px;
    }
    
    .order_product_option {
        width: 100%;
    }
 
/* 상품 수량 btn */
    .pro_btn {
        width:35px; 
        height:27px; 
        margin-left:3px; 
        margin-right:3px; 
        text-align:center;
    }
 
    .pro_totalPrice {
        font-weight: bold;
    }
 
/* 상품 삭제 버튼 div */
    .cart_btn_div {
        width: 100%;
        display: flex;
        margin: 20px;
    }
    
    .delete_btn {
        justify-content: space-between;
    }
    
    .order_btn {
        justify-content: space-evenly; 
    }
 
/* 장바구니 하단 총 요약 */
    .cart_table_option {
        width: 90%;
        display: flex;
        flex-direction: column;
        align-items: center;
    }
    
    .cart_total {
        display: flex;
        flex-direction: row;
        width: 95%;
        align-items: center;
        background-color: #f7f7f7;
        padding: 25px;
        margin-top: 30px;    
        border-top: 2px solid black;
    }
    
    .cart_option_table {
        list-style-type: none;
        display: flex;
        flex-direction: row;
        padding-left: 0px;
        width: 80%;
        align-items: center;
    }
    .cart_option_td {
        width: 100%;
        height: 30px;
        display: flex;
        align-items: center;
        justify-content: center;
        padding-top:10px;
    }
    .cart_total_ul {
        display: flex;
        width: 90%;
        justify-content: space-around;
        padding-left: 0px;
        flex-direction: column;
        align-items: center;
    }
    
    .cart_total_li {
        list-style-type: none;
    }
    
    .cart_total_li.val {
        font-size: x-large;
        font-weight: bold;
        text-align: center;
    }
    
    .cart_total_buho {
        font-weight: bold;
        font-size: xx-large;
        list-style-type: none;
    }
 
/* 옵션 버튼 */
    .cart_btn {
        border: 2px solid #dfdfdf !important;
        background-color: white !important;;
    } 
    
    .cart_btn:hover {
        border: 2px solid dimgrey !important;
        background-color: white !important;;
    } 
    
/* 전체 주문 버튼 */
    #orderAll {
        background-color: black !important;
        color: white !important;
    }
    
    #orderAll:hover {
        background-color: dimgrey !important;
    }
 

 

>> 실행

 

>>> 수량이 1일 때 - 버튼을 클릭하는 경우 alert을 띄우고 수량을 1로 고정합니다.

 

 

>>> 수량이 변경되는 경우 하단의 총 비용까지 변경

 

>>> 총 상품 금액이 50000원이 넘어가는 경우 배송비 0으로 변경됨

 

 

-- 상품 삭제 기능 구현

1. client_cart.js 파일 수정

-- 선택 삭제

-- 전체 삭제

-- 체크박스 선택시 하단의 결제 금액 변경

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
// 가격 지정
$(document).ready(function(){
    setPrice();
});
 
// 체크박스 선택(주문용)
let checkList = [];
 
// 체크박스 선택(삭제용)
let deleteList = [];
 
let checkCounts = document.querySelectorAll(".check");
 
// 선택 상품 삭제
function deleteSelect(){
    // 선택된 상품 없는 경우
    if(deleteList.length == 0){
        alert("삭제할 상품을 선택해주세요");
        return;
    }
    
    let proIdDiv;
    deleteList.forEach((check,index) => {
        proIdDiv = document.querySelector("#"+check);
        proIdDiv.closest(".cart_content.checklist").remove();
    });
    
    checkList.splice(0, checkList.length);
    deleteList.splice(0, deleteList.length);
    
    checkCounts = document.querySelectorAll(".check");
    setPrice();
}
 
// 전체 상품 삭제
function deleteAll(){
    checkCounts = document.querySelectorAll(".check");
    let proIdDiv;
    
    checkCounts.forEach((check,index) => {
        proIdDiv = document.querySelector("#"+check.value);
        proIdDiv.closest(".cart_content.checklist").remove();
    });
    checkList.splice(0, checkList.length);
    deleteList.splice(0, deleteList.length);
    
    checkCounts = document.querySelectorAll(".check");
    setPrice();
}
 
$(function(){
    $("#checkAll").click(function(){
        $(".check").prop("checked"this.checked);
        checkCounts = document.querySelectorAll(".check");
        
        if(this.checked){
            checkCounts.forEach((check, index) => {
                pushList(checkList, check.value);
                pushList(deleteList, check.value);
            });
        } else {
            checkCounts.forEach(check => {
                spliceList(checkList, check.value);
                spliceList(deleteList, check.value);
            });
        }
        setPrice();
    });
    
    $(".check").click(function(){
        
        if(this.checked){
            // 첫 화면시 모두 추가되어 있는 상태
            if(checkList.length == $(".checklist .check").length){
                checkList.splice(0, checkList.length);
            }
            
            pushList(checkList, this.value);
            pushList(deleteList, this.value);
        } else {
            spliceList(checkList, this.value);
            spliceList(deleteList, this.value);
        }
        
        if($(".check:checked").length < $(".checklist .check").length){
            $("#checkAll").prop("checked"false);
        } else {
            $("#checkAll").prop("checked"true);
        }
        setPrice();
    });
});
 
// list에 추가
function pushList(list, Value){
    const index = list.indexOf(Value);
    
    // 인덱스에 없는 경우
    if(index == -1){
        list.push(Value);
    }
}
 
// list에서 제거
function spliceList(list, Value) {
    const index = list.indexOf(Value);
 
    // 인덱스에 있는 경우
    if(index !== -1){
        list.splice(index, 1);
    }
}
 
// checkList 아무것도 없을 때
function checkNone(){
    // 상품별 count li 태그 찾기
    const cartCounts = document.querySelectorAll(".cart_con.count");
    cartCounts.forEach(cartId => {
        checkList.push(cartId.querySelector(".cartValue").id);
    });
}
 
// 값 설정
function setPrice(){
    let totalPriceVal = 0;
    let deliPriceVal = 3000;
    
    if(checkList == ''){
        checkNone();
    }
    
    // 상품별
    checkList.forEach(check => {
        
        // proId
        const proId = check;
 
        // 수량
        const countInput = document.querySelector("input[name='" + proId + "']");
        
        // 기본 가격
        const oriPriceInput = document.querySelector("input[name='" + proId + "_oriPrice']");
        
        const priceDiv = document.querySelector("#" + proId + "_price");
        const pro_totalPriceSpan = priceDiv.querySelector("#" + proId + "_totalPrice");
        const pro_totalPriceInput = priceDiv.querySelector("input");
        
        // (기본가격 * 수량)
        let pro_totalPrice = countInput.value * oriPriceInput.value
        
        pro_totalPriceSpan.innerHTML = setFormat(pro_totalPrice);
        pro_totalPriceInput.value = pro_totalPrice;
 
        // 총 상품 금액
        totalPriceVal += pro_totalPrice;                
    });
    
    // 배송비 조건부 무료
    if(totalPriceVal > 50000 || totalPriceVal == 0){
        deliPriceVal = 0;
    }
 
    // input
    const totalPriceInput = document.querySelector("input[name='totalPrice']");
    const deliPriceInput = document.querySelector("input[name='deliPrice']");
    const endPriceInput = document.querySelector("input[name='endPrice']");
    
    //span
    const totalPriceSpan = document.querySelector("#totalPrice");
    const deliPriceSpan = document.querySelector("#deliPrice");
    const endPriceSpan = document.querySelector("#endPrice");
    
    totalPriceInput.value = totalPriceVal;
    deliPriceInput.value = deliPriceVal;
    endPriceInput.value = totalPriceVal + deliPriceVal;
    
    totalPriceSpan.innerHTML = setFormat(totalPriceVal);
    deliPriceSpan.innerHTML = setFormat(deliPriceVal);
    endPriceSpan.innerHTML = setFormat(totalPriceVal + deliPriceVal);
}
 
// 수량 증가
function count(num, name) {
    const countInput = document.querySelector("input[name='" + name + "']");
    const pro_oriPriceInput = document.querySelector("input[name='" + name + "_oriPrice']");
    const pro_totalPriceInput = document.querySelector("input[name='" + name + "_totalPrice']");
    const pro_totalPriceSpan = document.querySelector("#" + name + "_totalPrice");
 
    let cnt = parseInt(countInput.value);
    let pro_oriPrice = parseInt(pro_oriPriceInput.value);
    let pro_totalPrice = parseInt(pro_totalPriceInput.value);
    
    if (num == 1) { // 수량 증가
        pro_totalPrice += pro_oriPrice;
        cnt++;
    } else if (num == 2){ // 수량 감소
        pro_totalPrice -= pro_oriPrice;
        cnt--;
    }
    
    if(cnt < 1){
        alert("수량은 1개 이상이어야 합니다.");
        cnt = 1;
        pro_totalPrice = pro_oriPrice;
    }
    
    countInput.value = cnt;
    pro_totalPriceInput.value = pro_totalPrice;
    pro_totalPriceSpan.innerHTML = setFormat(pro_totalPrice);
    
    setPrice();
}
 
// 숫자 표기
function setFormat(num){
    let result = num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    return result;
}

 

>> 실행

 

 

> 체크박스 하나 선택시 하단 가격 변동

 

 

> 체크하지 않은 상품 수량 변경해도 값 적용 안됨

 

 

> 체크한 상품 수량 변경 시 금액 변경됨

 

 

> 체크 전체 해제시 전체 상품 금액으로 자동 변경

 

 

>> 선택 삭제 기능

 

 

>> 전체 삭제 기능

 

 

>>> 추후 상품 상세에서 옵션/수량 선택 후 장바구니로 넘어오는 기능 작업 예정

-- 생각해 볼 부분

1) 비회원인 경우 작업하는 방법

---- 현재 cart 테이블의 cId는 client 테이블의 cId를 참조하므로 쿠키정보로 처리하려고 하면 제약조건에 위반됨

반응형