聯級選擇

<!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://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.js"></script>
    <title>Document</title>
</head>
<style>

</style>

<body>
    <select id="province" name="province">
        <option value="select">請選擇...</option>    
        <option value="hebei">河北省</option>    
        <option value="liaoning">遼寧省</option>    
        <option value="shandong">山東省</option>            
    </select>
    
    <select name="city">
        <option value="select">請選擇...</option>    
        
    </select>
    <script type="text/javascript">
        $(function(){
            var liaoning_city = ["瀋陽", "大連", "鞍山", "錦州", "丹東"];            
            var hebei_city = ["石家莊", "唐山", "秦皇島", "衡水", "保定"];
            var shandong_city = ["濟南", "青島","煙臺市","淄博"];
            
            $("select[name='province']").change(function() {
                //被選中的option
                var selected_value = $(this).val();
                
                if(selected_value == "select"){
                    $("select[name='city']").empty();
                    var option = $("<option>").val('請選擇...').text('請選擇...');
                          $("select[name='city']").append(option);
                    
                }else if(selected_value == "liaoning"){ //安徽
                    $("select[name='city']").empty();
                    //循環添加
                    for(var i = 0; i < liaoning_city.length; i++) {
                        var option = $("<option>").val(liaoning_city[i]).text(liaoning_city[i]);
                          $("select[name='city']").append(option);
                    }
                    
                }else if(selected_value == "hebei"){ //河北
                    $("select[name='city']").empty();
                    //循環添加
                    for(var i = 0; i < hebei_city.length; i++) {
                        var option = $("<option>").val(hebei_city[i]).text(hebei_city[i]);
                          $("select[name='city']").append(option);
                    }
                    
                }else if(selected_value == "shandong"){ //山東
                     $("select[name='city']").empty();
                    //循環添加
                    for(var i = 0; i < shandong_city.length; i++) {
                        var option = $("<option>").val(shandong_city[i]).text(shandong_city[i]);
                          $("select[name='city']").append(option);
                    }
                }
            });
                            
        });
</script>
</body>

</html>

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章