Handling Multiple dependent drop down lists in a form using Django and jquery
I want to create a form with 4 drop down list in which two of them are dependent on the other two, example i have a country and city drop list in which the city is dependent on the country i.e. when a country is selected only cities in that country will show in the city drop down and its working perfectly but my department and unit are not working as expected. I wand same for my department and units, if a department is selected only units in that department should show. I want to implement this in one form.
<form method="post" enctype="multipart/form-data" autocomplete='off' class="mt-3" novalidate id="personForm" data-cities-url="{% url 'ajax_load_cities' %}" data-units-url="{% url 'ajax_load_units' %}">
<div class="row">
<div class="col-3">{{ form.country|as_crispy_field}}</div>
<div class="col-3">{{ form.city|as_crispy_field}}</div>
<div class="col-3">{{ form.department|as_crispy_field}}</div>
<div class="col-3">{{ form.unit|as_crispy_field}}</div>
</div>
<script>
$("#id_country").change(function () {
const url = $("#personForm").attr("data-cities-url");
const countryId = $(this).val();
$.ajax({
url: url,
data: {
'country_id': countryId
},
success: function (data) {
console.log(data);
$("#id_city").html(data);
});
}
});
});
$("#id_department").change(function () {
const url = $("#personForm").attr("data-units-url");
const departmentId = $(this).val();
$.ajax({
url: url,
data: {
'department_id': departmentId
},
success: function (data) {
console.log(data);
$("#id_unit").html(data);
}
});
});
</script>