|
| 1 | +document.addEventListener("DOMContentLoaded", () => { |
| 2 | + const form = document.querySelector('.user-registration-form'); |
| 3 | + |
| 4 | + // Handle form submission |
| 5 | + form.addEventListener('submit', (e) => { |
| 6 | + e.preventDefault(); |
| 7 | + |
| 8 | + // Collect form data |
| 9 | + const fullName = form.querySelector('input[placeholder="Full Name"]').value.trim(); |
| 10 | + const phoneNumber = form.querySelector('input[placeholder="Phone Number"]').value.trim(); |
| 11 | + const emailId = form.querySelector('input[placeholder="Email ID"]').value.trim(); |
| 12 | + const comments = form.querySelector('textarea[placeholder="Comments"]').value.trim(); |
| 13 | + |
| 14 | + // Client-side validation |
| 15 | + if (!fullName || !phoneNumber || !emailId || !comments) { |
| 16 | + alert('Please fill out all required fields.'); |
| 17 | + return; // Stop the submission if validation fails |
| 18 | + } |
| 19 | + |
| 20 | + // Log the form data in the console |
| 21 | + const formData = { |
| 22 | + fullName, |
| 23 | + phoneNumber, |
| 24 | + emailId, |
| 25 | + comments, |
| 26 | + }; |
| 27 | + console.log(formData); // Log collected data |
| 28 | + |
| 29 | + // Export options |
| 30 | + const exportType = prompt("Type 'CSV' for CSV export or 'EXCEL' for Excel export:"); |
| 31 | + |
| 32 | + if (exportType.toLowerCase() === 'csv') { |
| 33 | + exportToCSV(formData); |
| 34 | + } else if (exportType.toLowerCase() === 'excel') { |
| 35 | + exportToExcel(formData); |
| 36 | + } else { |
| 37 | + alert("Invalid option selected."); |
| 38 | + } |
| 39 | + |
| 40 | + // Reset form |
| 41 | + form.reset(); |
| 42 | + }); |
| 43 | + |
| 44 | + // Function to export data to CSV |
| 45 | + function exportToCSV(data) { |
| 46 | + const csvContent = `Full Name,Phone Number,Email ID,Comments\n${data.fullName},${data.phoneNumber},${data.emailId},${data.comments}`; |
| 47 | + const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' }); |
| 48 | + const link = document.createElement('a'); |
| 49 | + const url = URL.createObjectURL(blob); |
| 50 | + link.setAttribute('href', url); |
| 51 | + link.setAttribute('download', 'form_data.csv'); |
| 52 | + document.body.appendChild(link); |
| 53 | + link.click(); |
| 54 | + document.body.removeChild(link); |
| 55 | + } |
| 56 | + |
| 57 | + // Function to export data to Excel |
| 58 | + function exportToExcel(data) { |
| 59 | + const workbook = XLSX.utils.book_new(); |
| 60 | + const worksheetData = [['Full Name', 'Phone Number', 'Email ID', 'Comments'], |
| 61 | + [data.fullName, data.phoneNumber, data.emailId, data.comments]]; |
| 62 | + |
| 63 | + const worksheet = XLSX.utils.aoa_to_sheet(worksheetData); |
| 64 | + XLSX.utils.book_append_sheet(workbook, worksheet, 'Form Responses'); |
| 65 | + |
| 66 | + XLSX.writeFile(workbook, 'form_data.xlsx'); |
| 67 | + } |
| 68 | +}); |
0 commit comments