I have a script that loads a dependent drop-down options. I added a part where the dependent drop-down hides whenever there are no options available. The primary drop-down retains the most recent submission data after being submitted, but when you submit an option that has no options on the secondary drop-down, and the page reloads, the primary drop-down, with the option that has no secondary options shows, and also the secondary drop-down, and when you click it it's just empty, because the logic that checks whether it should be hidden or not only checks when there's a change in the primary drop-down. How can I change this script at the end so that it loads both at the beginning and when there are changes?
enter_exit_area.html
{% extends "base.html" %}
{% load core_tags staticfiles %}
{% block main %}
<form id="warehouseForm" action="" method="POST" data-stations-url="{% url 'operations:ajax_load_stations' %}" novalidate >
{% csrf_token %}
<div>
<div>
<label>Employee #</label>
{{ form.employee_number }}
</div>
<div>
<label>Work Area</label>
{{ form.work_area }}
</div>
<div id="my-hidden-div">
<label>Station</label>
{{ form.station_number }}
</div>
</div>
<div>
<div>
<button type="submit" name="enter_area" value="Enter">Enter Area</button>
<button type="submit" name="leave_area" value="Leave">Exit Area</button>
</div>
</div>
</form>
<script>
$("#id_work_area").change(function () {
var url = $("#warehouseForm").attr("data-stations-url");
var workAreaId = $(this).val();
var $stationNumberField = $("#{{ form.station_number.id_for_label }}");
$.ajax({
url: url,
data: {
'work_area': workAreaId
},
success: function (data) {
$("#my-hidden-div").show(); // show it
$stationNumberField.html(data);
// Check the length of the options child elements of the select
if ($stationNumberField.find("option").length === 1) {
$stationNumberField.parent().hide(); // Hide parent of the select node
} else {
// If any option, ensure the select is shown
$stationNumberField.parent().show();
}
}
});
});
</script>
{% endblock main %}