Сначала давайте восстановим данные JSON, чтобы они содержали идентификатор опции (для использования id
для значения опции)
[
{
id: 1,
name: "Chandigarh",
regions: [
{
id: 2,
name: "CHANDIGARH",
areas: [
{ id: 3, name: "Sector 21 (Chandigarh)" },
{ id: 4, name: "Sector 22 (Chandigarh)" },
{ id: 5, name: "Sector 23 ( Chandigarh)" },
{ id: 6, name: "Sector 26 (Chandigarh)" },
{ id: 7, name: "Sector 29 (Chandigarh)" },
{ id: 8, name: "Sector 30" }
]
}
]
},
{
id: 9,
name: "Andhra Pradesh",
regions: [
{
id: 10,
name: "EAST GODAVARI",
areas: [
{ id: 11, name: "D Vemavaram" },
{ id: 12, name: "Gangavaram" },
{ id: 13, name: "GSL Medical College" },
{ id: 14, name: "Konthamuru" },
{ id: 15, name: "Navara" },
{ id: 16, name: "Satellite City" }
]
},
{
id: 17,
name: "CHITTOOR",
areas: [
{ id: 18, name: "Appa Rao Street" },
{ id: 19, name: "Madanapalle Spinning Mills Gds" },
{ id: 20, name: "Akkurthi" },
{ id: 21, name: "Chiyyavaram" },
{ id: 22, name: "Chodavaram" },
{ id: 23, name: "Gottipudi" },
{ id: 24, name: "Kasaram" },
{ id: 25, name: "Muchivolu" },
{ id: 26, name: "Obulayapalle" }
]
}
]
}
]
Обновить код выборки, чтобы сохранить данные в переменной.
var states;
$.getJSON(url, function (data) {
states = data; // Save data to variable, so no need to fetch data everytime user change the select
$("#state").html(`<option>Select State..</option>`);
$("#region").html(`<option>Select region..</option>`);
$("#area").html(`<option>Select area..</option>`);
$.each(states, function (index, state) {
$('#state').append(`<option value="${state.id}">${state.name}</option>`);
});
});
Затем назначьте событие для выбора
$("#state").bind("change", function() { // When select state change
let state = states.find(s => s.id == $(this).val());
// set region options
$("#region").html(`<option>Select region..</option>`);
$.each(state.regions, function(index, region) {
$("#region").append(`<option value="${region.id}">${region.name}</option>`);
});
$("#area").html(`<option>Select area..</option>`);
});
$("#region").bind("change", function() { // When select region change
let region = states
.map(s => s.regions)
.flat()
.find(r => r.id == $(this).val());
// set area options
$("#area").html(`<option>Select area..</option>`);
$.each(region.areas, function(index, area) {
$("#area").append(`<option value="${area.id}">${area.name}</option>`);
});
});
Здесь для полного примера
https://codesandbox.io/s/5k87rkr16p