Closed
Description
I am trying to show popup on submission of Contact form. This script is not running when the page loads first time but it works when form is already submitted and try to submit again. I tried on both src/page/contact.astro
and src/components/ui/Form.astro
but neither works.
<script is:inline>
document.addEventListener("DOMContentLoaded", function() {
const form = document.getElementById('formId');
if (!form) {
console.warn('Form element not found on first load');
return; // Early exit if form element is missing
}
const popup = document.getElementById('submittingPopup');
const successMessage = document.getElementById('successMessage');
const submittingText = popup ? popup.querySelector('p.text-lg') : null;
console.log(form, popup, successMessage, submittingText);
function handleSubmit(e) {
if (!document.getElementById('disclaimer').checked) {
e.preventDefault();
alert('Please accept the terms.');
return;
}
e.preventDefault();
popup.classList.remove('hidden');
if (submittingText) submittingText.textContent = "Submitting";
successMessage.classList.add('hidden');
const data = new FormData(form);
fetch(form.action, { method: 'POST', body: data })
.then(() => {
document.querySelector('.loader').classList.add('hidden');
if (submittingText) submittingText.textContent = "Submitted";
successMessage.classList.remove('hidden');
})
.catch(error => {
console.error('Error:', error);
alert('Submission failed. Please try again.');
})
.finally(() => {
setTimeout(() => {
popup.classList.add('hidden');
successMessage.classList.add('hidden');
document.querySelector('.loader').classList.remove('hidden');
}, 2000);
});
}
form.addEventListener("submit", handleSubmit);
});
</script>
Metadata
Metadata
Assignees
Labels
No labels