71 lines
2.9 KiB
JavaScript
71 lines
2.9 KiB
JavaScript
document.addEventListener('DOMContentLoaded', function () {
|
|
const divisionSelect = document.getElementById('division_id');
|
|
const departmentSelect = document.getElementById('department_id');
|
|
const roleSelect = document.getElementById('role_id');
|
|
|
|
const initialDepartmentId = departmentSelect.dataset.initial;
|
|
const initialRoleId = roleSelect.dataset.initial;
|
|
|
|
function fetchDepartments(divisionId, selectedDepartmentId) {
|
|
return fetch(`api.php?action=get_departments&division_id=${divisionId}`)
|
|
.then(response => response.json())
|
|
.then(data => {
|
|
departmentSelect.innerHTML = '<option value="">Select Department</option>';
|
|
data.forEach(department => {
|
|
const option = document.createElement('option');
|
|
option.value = department.id;
|
|
option.textContent = department.name;
|
|
if (department.id == selectedDepartmentId) {
|
|
option.selected = true;
|
|
}
|
|
departmentSelect.appendChild(option);
|
|
});
|
|
});
|
|
}
|
|
|
|
function fetchRoles(departmentId, selectedRoleId) {
|
|
// Only fetch if a department is selected
|
|
if (!departmentId) {
|
|
roleSelect.innerHTML = '<option value="">Select Role</option>';
|
|
return Promise.resolve(); // Return a resolved promise
|
|
}
|
|
|
|
return fetch(`api.php?action=get_roles&department_id=${departmentId}`)
|
|
.then(response => response.json())
|
|
.then(data => {
|
|
roleSelect.innerHTML = '<option value="">Select Role</option>';
|
|
data.forEach(role => {
|
|
const option = document.createElement('option');
|
|
option.value = role.id;
|
|
option.textContent = role.name;
|
|
if (role.id == selectedRoleId) {
|
|
option.selected = true;
|
|
}
|
|
roleSelect.appendChild(option);
|
|
});
|
|
});
|
|
}
|
|
|
|
divisionSelect.addEventListener('change', function () {
|
|
const divisionId = this.value;
|
|
fetchDepartments(divisionId, null).then(() => {
|
|
// After departments are loaded, fetch roles for the (now cleared) department selection
|
|
fetchRoles(departmentSelect.value, null);
|
|
});
|
|
});
|
|
|
|
departmentSelect.addEventListener('change', function () {
|
|
const departmentId = this.value;
|
|
fetchRoles(departmentId, null);
|
|
});
|
|
|
|
// Initial load
|
|
if (divisionSelect.value) {
|
|
fetchDepartments(divisionSelect.value, initialDepartmentId).then(() => {
|
|
// After initial departments are loaded and correct one is selected,
|
|
// fetch the roles for that department.
|
|
fetchRoles(departmentSelect.value, initialRoleId);
|
|
});
|
|
}
|
|
});
|