ccah-assessment/assets/js/main.js

98 lines
3.4 KiB
JavaScript

document.addEventListener("DOMContentLoaded", function () {
// 🚀 Automatically load existing responses if available
fetch("load-responses.php")
.then(response => response.json())
.then(data => prepopulateForm(data))
.catch(error => console.error("Failed to load form responses:", error));
// 🚀 Handle Form Submission via AJAX
document.getElementById("assessment-form").addEventListener("submit", function (event) {
event.preventDefault(); // Prevent normal form submission
const formData = new FormData(this);
fetch("submit.php", {
method: "POST",
body: formData
})
.then(response => response.json())
.then(data => {
if (data.success) {
showMessage("success", data.success);
} else {
showMessage("danger", data.error || "Something went wrong.");
}
})
.catch(error => {
console.error("Submission error:", error);
showMessage("danger", "Failed to submit the form.");
});
});
// 🚀 Dynamic Fields - Show/Hide Textboxes Based on Selection
document.querySelectorAll("input[type=checkbox], input[type=radio], select").forEach(input => {
input.addEventListener("change", function () {
toggleDependentFields();
});
});
// Initial check on page load
toggleDependentFields();
});
// ✅ Prepopulate the form with existing responses
function prepopulateForm(data) {
if (data.error) {
console.error("Error loading responses:", data.error);
return;
}
Object.keys(data).forEach(key => {
let input = document.querySelector(`[name="${key}"]`);
if (!input) return;
if (input.type === "checkbox" || input.type === "radio") {
document.querySelectorAll(`[name="${key}"]`).forEach(option => {
option.checked = data[key].includes(option.value);
});
} else {
input.value = data[key];
}
});
toggleDependentFields(); // Ensure dependent fields are updated
}
// ✅ Show message function (Bootstrap alert)
function showMessage(type, message) {
let messageDiv = document.getElementById("form-message");
messageDiv.className = `alert alert-${type}`;
messageDiv.textContent = message;
messageDiv.classList.remove("d-none");
}
// ✅ Handle Conditional Fields (Show/Hide)
function toggleDependentFields() {
let toggleMappings = {
"mfa": ["mfa-types-section"],
"mfa_types[]": ["mfa-app-section"],
"personal_device": ["device-options-section"],
"board_doc_access": ["access_issues_details"],
"meeting_issues": ["meeting_issues_details"],
"it_challenges[]": ["it-challenges-other-text"],
"security_concerns[]": ["security-other-text"],
"file_storage[]": ["file-storage-other-text"],
"critical_files[]": ["critical-files-other-text"]
};
Object.keys(toggleMappings).forEach(trigger => {
let elements = document.querySelectorAll(`[name="${trigger}"]`);
let targetIds = toggleMappings[trigger];
let shouldShow = Array.from(elements).some(el => el.checked && el.value === "Other" || el.value === "Yes");
targetIds.forEach(id => {
document.getElementById(id).style.display = shouldShow ? "block" : "none";
});
});
}