自动填写表格与国家,城市等

时间:2016-07-07 19:32:07

标签: javascript forms

如果我有一个用户选择国家/地区的表单,那么他们会选择该国家/地区的州,然后选择该州的州。最简单的方法是什么,所以当他们选择国家时,它会更新州表格等等?我想他们是一个通用的JavaScript库吗?

1 个答案:

答案 0 :(得分:1)

试一试:



<html>

<head>
    <style>
        .sel {
            width: 200px;
        }
    </style>
</head>
<body>
    Country : <select id="contry" class="sel"><option value=""></option></select><br><br>
    State : <select id="state" class="sel"></select>
    <script>
        var contry = [
            {id:"Iran",state:['Tehran','Ahvaz','Shiraz']},
            {id:"Usa",state:['Alabama','Alaska','Florida']}
        ]
        var con = document.getElementById("contry");
        var sta = document.getElementById("state");
        for(var i=0; i<contry.length; i++) {
            var op = document.createElement('option');
            op.value = contry[i].id;
            op.innerHTML = contry[i].id;
            con.appendChild(op);
        }
        con.onchange= function() {
            sta.innerHTML = "";
            var cur = con.value;
            if(cur.length > 0 ) {
                for (var j = 0; j < contry.length; j++)
                    if (cur == contry[j].id) {
                        var myState = contry[j].state;
                        break;
                    }
                for(var i=0; i<myState.length; i++) {
                var op = document.createElement('option');
                op.value = myState[i];
                op.innerHTML = myState[i];
                sta.appendChild(op);
        }
                
                        
            }
        }
        
   </script>
</body>     
</html> 
&#13;
&#13;
&#13;