document.addEventListener(‘DOMContentLoaded’, () => {
const form = document.getElementById(‘form’);
const warningDiv = document.getElementById(‘warning’);
if (!form || !warningDiv) {
console.error('Form or warning div not found');
return;
}
// Function to get form data
function handleGetFormData() {
const name = document.getElementById('name').value.trim();
const email = document.getElementById('email').value.trim();
const city = document.getElementById('city').value.trim();
const dob = document.getElementById('dob').value.trim();
const gender = document.querySelector('input[name="gender"]:checked')?.value;
const password = document.getElementById('password').value.trim();
const zipCode = document.getElementById('zip-code').value.trim();
const status = document.getElementById('status').checked;
return { name, email, city, dob, gender, password, zipCode, status };
}
// Function to check if a string is a number
function isNumber(string) {
return !isNaN(string) && !isNaN(parseFloat(string));
}
// Function to check if the checkbox is checked
function checkboxIsChecked() {
return document.getElementById('status').checked;
}
// Function to validate form data
function validateFormData(data) {
return data &&
data.name &&
data.city &&
data.email &&
data.dob &&
data.gender &&
data.password &&
isNumber(data.zipCode) &&
checkboxIsChecked();
}
// Form submit event listener
document.getElementById(‘submit-form’).addEventListener(‘click’, (event) => {
event.preventDefault();
submit();
});
// Clear previous warnings
warningDiv.innerHTML = '';
// Get form data
const formData = handleGetFormData();
console.log('Form Data:', formData);
// Validate form data
if (validateFormData(formData)) {
// If no errors, submit the form data (for this example, just display an alert)
alert('Form submitted successfully!');
// Here you can add code to actually submit the form data to the server
} else {
warningDiv.innerHTML = 'Periksa form anda sekali lagi';
console.warn('Form validation failed');
}
}
// Attach submit event listener to the form
form.addEventListener('submit', submit);
});