[js] selectbox 선택에 따라 option 변경

florentyoon·2021년 2월 17일
0

js

목록 보기
5/12

selectbox에서 선택한 option에 따라서 두 번째 selectbox의 option이 변경되는 스크립트.

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
  
    <script
    src="https://code.jquery.com/jquery-3.5.1.js"
    integrity="sha256-QWo7LDvxbWT2tbbQ97B53yJnYU3WhH/C8ycbRAkjPDc="
    crossorigin="anonymous"></script>
    <script src="test.js"></script>
    <script src="common.js"></script>
</head>
<body>
    <div class="box-body">
        <h5>물품</h5>
        <div class="input-group">
            <span class="input-group-addon"><i class="fa fa-building"></i></span>
            <select class="form-control" name="user_type">
                <option value="">선택</option>
                <option value="과일">과일</option>
                <option value="생선">생선</option>
            </select>
        </div>
        <h5>종류</h5>
        <div class="input-group">
            <span class="input-group-addon"><i class="fa fa-building"></i></span>
            <select class="form-control" name="type">
                <option value="">선택</option>
            </select>
        </div>
    </div>
</body>
</html>

test.js


$(function(){
    $('select[name="user_type"] ').on('change', function()  {
        let arrType = getAgreeType();
        let optionType = $(this).parents('.box-body').find($('select[name="type"]'));
        optionType.empty();

        if($(this).val() == '과일'){ 
            for(prop in arrType['과일']){
                optionType.append('<option value='+prop+' >'+arrType['과일'][prop]+'</option>');
            }
        }else{                            
            for(prop in arrType['생선']){
                optionType.append('<option value='+prop+' >'+arrType['생선'][prop]+'</option>');
            }                  
        }        
    });
});

common.js

function getAgreeType() {    
    var obj = {
        "과일" : {
            'apple' : '사과',
            'pear' : '배',
            'melon' : '메론',
            'banana' : '바나나',            
        },
        "생선" : {
            'mackerel' : '고등어',
            'anchovy' : '멸치',
            'tuna' : '참치',
            'salmon' : '연어',
        }
       
    }
    return obj;
}
profile
florentyoon의 IT 세상

0개의 댓글