برای نمایش روش کار یک فایل html ساده با 4 کمبو درست میکنیم:
<body>
<form id="form1" action="">
<div id="fields">
<label for="cb_State">استان:</label>
<select id="cb_State">
<option value="-1">----</option>
</select>
<label for="cb_County">شهرستان:</label>
<select id="cb_County">
<option value="-1">----</option>
</select>
<label for="cb_District">بخش:</label>
<select id="cb_District">
<option value="-1">----</option>
</select>
<label for="cb_City">شهر:</label>
<select id="cb_City">
<option value="-1">----</option>
</select>
<label></label>
<input type="submit" value="Submit">
</div>
</form>
</body>
و کدهای جاوااسکریپت رو اضافه میکنیم:
<script src="data.js"></script>
<script>
var Counties; // شهرستانها
var Districts; // بخشها
var Cities; // شهرها
window.onload = function () {
States.forEach(function (x) {
cb_State.add(new Option(x.State, x.StateID));
});
cb_State.selectedIndex = 0;
cb_State.onchange = function () {
cb_County.length = 1;
cb_District.length = 1;
cb_City.length = 1;
var selected_StateID = this.value;
if (selected_StateID !== '-1') {
Counties = States.find(x => x.StateID == selected_StateID).Counties;
Counties.forEach(function (x) {
cb_County.add(new Option(x.County, x.CountyID));
});
};
};
cb_County.onchange = function () {
cb_District.length = 1;
cb_City.length = 1;
var selected_CountyID = this.value;
if (selected_CountyID !== '-1') {
Districts = Counties.find(x => x.CountyID == selected_CountyID).Districts;
Districts.forEach(function (x) {
cb_District.add(new Option(x.District, x.DistrictID));
});
};
};
cb_District.onchange = function () {
cb_City.length = 1;
var selected_DistrictID = this.value;
if (selected_DistrictID !== '-1') {
Cities = Districts.find(x => x.DistrictID == selected_DistrictID).Cities;
Cities.forEach(function (x) {
cb_City.add(new Option(x.City, x.CityID));
});
};
};
};
</script>
فایل پیوست شامل demo.html با 4 کمبو آبشاری و data.js با اطلاعات زیر هست:
31 استان
474 شهرستان
1163 بخش
1431 شهر