본문 바로가기
웹 개발자 준비 과정🐳

day10 : jquery 를 이용하여 장바구니 기능 구현하기

by @ENFJ 2022. 8. 1.

 

day10 : jquery 를 이용하여 장바구니 기능 구현하기

 

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/css/bootstrap.min.css">
    <script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.slim.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://unpkg.com/underscore@1.13.4/underscore-umd-min.js"></script>
<!-- CSS -->
<style>
   

    .legends { 
        width: 100px;
        padding-left: 0px;
        margin-left: 10px;
        padding-right: 0px;
    }
    .baguni {
        border: solid 1px black;
        margin-left: 200px;
        margin-right: 200px;
        border-left-width: 1px;
        padding-left: 15px;
        height: 102px;
        width: auto;
        height: auto;
    }

    #sumBox {
        margin-left: 200px;
    }
</style>
</head>



<body>

<!-- jumbotron:전광판 -->
    <div class="jumbotron">
        <h1>길동이의 전자랜드</h1>
        <p>this is jumbotron </p>
    </div>

<!--input 영역-->
    <div class="container">
        <div class="inputBox">
            <label>제품명</label> <input type="text" id="name" value="킥보드"> | 
            <label>가격</label> <input type="text" id="price" value="130"> 
            <input type="button" id="saveBtn" value="Add">
        </div>
        <div class="listBox">

        </div>
        
    </div>

<!-- 테이블 -->
    <script type="text/template" id="tableTemplate">
        <table  class="table table-striped">

<!--테이블 헤드-->
            <thead>
                <th>번호</th>
                <th>제품명</th>
                <th>가격</th>
                <th>수량</th>
                <th>장바구니담기</th>
            </thead>


<!--테이블 body-->
            <tbody>
<!-- <% %> 이것으로 감싸여져 있는 부분은 JSP 코드중에 JAVA 구현부분 이부분은 서버에서 실행이 된다.-->
            <% 
            productList.forEach(function(item) {
            %>
                <tr>
                    <td><%= item.no %></td>
                    <td><%= item.name %></td>
                    <td><%= item.price %></td>
                    <td>
                        <select name="ea" class="ea">
                            <option value="1">1</option><option value="2">2</option><option value="3">3</option><option value="4">4</option><option value="5">5</option>
                        </select>
                    </td>
                    <td><a onclick='appendCart(this)' class="btn btn-primary" href="#">장바구니에저장</a></td>
                </tr>
            <% }); %>
            </tbody>
        </table>
    </script>
<hr/>
<fieldset class="baguni">
  <!--장바구니-->
    <legend class="legends">장바구니</legend>
   
</fieldset>

<div id="sumBox">
    총합계:
</div>

<!-- 장바구니 -->
<div>
    
</div>



<!--javascript(자바스크립트)-->
    <script>
    
    var sum = 0; //

        function appendCart(btn) {
            var $row = $(btn).parent().parent();
            var eaVal = $row.find('select[name=ea]').val();
            var noVal = $row.find("td:nth(0)").text();
            var nameVal = $row.find("td:nth(1)").text(); 
            var priceVal = $row.find("td:nth(2)").text();
            //console.log(noVal, eaVal);
            // sessionStorage 또는 localStorage에 저장.

            
            var br = document.createElement('br');
            sum += Number(eaVal) * Number(priceVal)
            $('.baguni').append(nameVal + " " + eaVal + "개" + " " + Number(eaVal) * Number(priceVal) + "만원");
            $('.baguni').append(br);

            var sumBox = document.getElementById("sumBox");
            sumBox.textContent = "총합계: " + sum + "만원";

        }

        function getTopNo(lis) {
            var topNo = -1;
            lis.forEach(function(item) {
                if(item.no > topNo) {
                    topNo = item.no;
                }
            });
            
            return topNo;
        }
function init(){ //
    if(!localStorage.getItem("productList")) {
            var list = [
                {"no":1,"name":"냉장고","price":300},
                {"no":2,"name":"세탁기","price":200},
                {"no":3,"name":"오디오","price":100},
                {"no":4,"name":"테레비","price":150},
                {"no":5,"name":"압력솥","price":50},
                {"no":6,"name":"에어콘","price":100},
                {"no":7,"name":"건조기","price":100},
                {"no":8,"name":"전자랜지","price":20},
                {"no":9,"name":"에어프라이기","price":30}
            ];
            // productList는 localStorage에 저장하고
            // 장바구니는 sessionStorage에 저장한다.
            localStorage.setItem("productList", JSON.stringify(list));
            localStorage.setItem("topNo", "" + getTopNo(list));
        }
}
// Add 버튼
        $('#saveBtn').on('click', function(e) {
            var rowItem = {
                no: Number(localStorage.getItem("topNo"))+1,
                name : $('#name').val(),
                price : $('#price').val()
            }
            var newList = JSON.parse(localStorage.getItem("productList"));
            newList.push(rowItem);
            console.log(newList);
            localStorage.setItem("topNo", "" + getTopNo(newList));
            localStorage.setItem("productList", JSON.stringify(newList));

// 목록 갱신
            loadData();
        });
        
        
        function loadData() {
            var productList = JSON.parse(localStorage.getItem("productList"));
            var compiled = _.template($('#tableTemplate').html());
            var html = compiled({productList: productList});
            $('div.listBox').html(html);
        }

        $(function() {
            init(); //
            loadData();
        });
    </script>

</body>
</html>