본문 바로가기

공부/JS , HTML , CSS

[javascript] select 옵션 선택마다 다른 사진 출력

1. 이미지 경로를 배열로 두고 한 방법

 

 

<!DOCTYPE html>
<html lang="en">
<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">
    <script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
    <title>Document</title>
    <style>
        .custom {
            text-align: right;
            float: right;
            width: 40%;
        }
        .imgfloat {
            float: left;
            width: 60%;
        }
        img {
            width: 450px;
            height: 450px;
        }
        .header {
            text-align: center;
            font-weight: bolder;
        }
        p {
            font-style: oblique;
        }
    </style>
    <script> // event 는 script로 모으기, 이미지의 이름 바꿔서 사진이랑 매칭하기
            console.log($("roomtype"))
            var img_arr = ["images/ruby1.jpg","images/emerald1.jpg","images/sky01.jpg", "images/star1.jpg"];
            
                function changeImg() {
                    var idx =$(".room option").index($(".room option:selected"));
                    console.log(idx);
                    console.log(img_arr[idx]);
                    document.getElementById("imgchg").src = img_arr[idx];
                }

                function calPrice() {
                    numBbq = Number($("input[name=addBbq]").val());
                    numBlk = Number($("input[name=addBlk]").val());
                    people = 2 + numBlk;
                    price = 100000 + 10000*(numBbq+numBlk) + 20000*people;
                    tax = price *0.1;
                    totalPrice = price + tax;
                    console.log(tax);
                    $("input[name=numPer]").val(people);
                    $("input[name=price]").val(price);
                    $("input[name=tax]").val(tax);
                    $("input[name=total]").val(totalPrice);

                    $(".result").html(
                        "<br>객실 : " + $(".room option:selected").val() +
                        "<br>바베큐 : " + numBbq +
                        "<br>이불수 : " + numBlk +
                        "<br>인원수 : " + people +
                        "<br>금액 : " + price +
                        "<br>세금 : " + tax +
                        "<br>총금액 : " + totalPrice
                        );
                        
                }
    </script>
</head>
<body>
    <div class="header">
        <h1>펜션예약사항</h1>
        <p>비수기 세일입니다. 펜션의 모든 방을 10만원에 단, 모든 방은 2인용입니다.!!</p>
    </div>
    <div class="custom">
        객실명 : <select class="room" onchange="changeImg()">
            <option class="roomtype" value="루비">루비</option>
            <option class="roomtype" value="에메랄드">에메랄드</option>
            <option class="roomtype" value="스카이1호">스카이1호</option>
            <option class="roomtype" value="별님실">별님실</option>
            </select> <br>
        바베큐시설이용 : <input name="addBbq" type="text"> <br>
        이불추가 : <input name="addBlk" type="text" onblur="calPrice()"> <br>
        인원수 : <input name="numPer" type="text"><br>
        금액 : <input name="price" type="text"><br>
        부과세 : <input name="tax" type="text"><br>
        총금액 : <input name="total" type="text"><br>
        <input type="button" value="Place Order"> <br>
        <span class="result"></span>
    </div>

    <div class="imgfloat">
        <img id="imgchg" src="D:\web\0217\images\pension.jpg">
    </div>
</body>
</html>

 

 

2. 이미지 이름 자체를 this로 받아서 이미지를 바꿀 수 있도록 함

<!DOCTYPE html>
<html lang="en">
<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">
    <script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
    <title>Document</title>
    <style>
        .custom {
            text-align: right;
            float: right;
            width: 40%;
        }
        .imgfloat {
            float: left;
            width: 60%;
        }
        img {
            width: 450px;
            height: 450px;
        }
        .header {
            text-align: center;
            font-weight: bolder;
        }
        p {
            font-style: oblique;
        }
    </style>
    <script> // event 는 script로 모으기, 이미지의 이름 바꿔서 사진이랑 매칭하기

            $(function(){

                $(".room").change(function(){
                    $("#imgchg").attr("src","images/"+$(this).val()+".jpg");
                })

                $("input[name=addBlk]").blur(function(){
                    numBbq = Number($("input[name=addBbq]").val());
                    numBlk = Number($("input[name=addBlk]").val());
                    people = 2 + numBlk;
                    price = 100000 + 10000*(numBbq+numBlk) + 20000*people;
                    tax = price *0.1;
                    totalPrice = price + tax;
                    console.log(tax);
                    $("input[name=numPer]").val(people);
                    $("input[name=price]").val(price);
                    $("input[name=tax]").val(tax);
                    $("input[name=total]").val(totalPrice);

                    $(".result").html(
                        "<br>객실 : " + $(".room option:selected").text() +
                        "<br>바베큐 : " + numBbq +
                        "<br>이불수 : " + numBlk +
                        "<br>인원수 : " + people +
                        "<br>금액 : " + price +
                        "<br>세금 : " + tax +
                        "<br>총금액 : " + totalPrice
                    );
                })
            })
    </script>
</head>
<body>
    <div class="header">
        <h1>펜션예약사항</h1>
        <p>비수기 세일입니다. 펜션의 모든 방을 10만원에 단, 모든 방은 2인용입니다.!!</p>
    </div>
    <div class="custom">
        객실명 : <select class="room">
            <option class="roomtype" value="pension">방선택</option>
            <option class="roomtype" value="ruby1">루비</option>
            <option class="roomtype" value="emerald1">에메랄드</option>
            <option class="roomtype" value="sky01">스카이1호</option>
            <option class="roomtype" value="star1">별님실</option>
            </select> <br>
        바베큐시설이용 : <input name="addBbq" type="text"> <br>
        이불추가 : <input name="addBlk" type="text"> <br>
        인원수 : <input name="numPer" type="text"><br>
        금액 : <input name="price" type="text"><br>
        부과세 : <input name="tax" type="text"><br>
        총금액 : <input name="total" type="text"><br>
        <input type="button" value="Place Order"> <br>
        <span class="result"></span>
    </div>

    <div class="imgfloat">
        <img id="imgchg" src="D:\web\0217\images\pension.jpg">
    </div>
</body>
</html>

 

 

수정된 부분이 보이시나요?? 2번 방법이 확실히 깔끔하고 편한 방법인 것 같요 실용적이고!

1번 방법에선 event구문도 html이랑 script에 섞여있어서 아무래도 보기 불편했는데

2번으로 바꾼 후 확실히 이해하기 편해졌어요

jquery가 없었으면 이것도 더 힘들었겠죠..?

다음엔 jquery 없이 도전해봐야 겠어요!