Spaces:
Running
Running
| document.addEventListener('DOMContentLoaded', function() { | |
| // Format card number input | |
| const cardNumberInput = document.getElementById('card-number'); | |
| cardNumberInput.addEventListener('input', function(e) { | |
| let value = e.target.value.replace(/\s+/g, ''); | |
| if (value.length > 0) { | |
| value = value.match(new RegExp('.{1,4}', 'g')).join(' '); | |
| } | |
| e.target.value = value; | |
| }); | |
| // Format expiry date input | |
| const expiryDateInput = document.getElementById('expiry-date'); | |
| expiryDateInput.addEventListener('input', function(e) { | |
| let value = e.target.value.replace(/\D/g, ''); | |
| if (value.length >= 2) { | |
| value = value.substring(0, 2) + '/' + value.substring(2); | |
| } | |
| e.target.value = value; | |
| }); | |
| // Only allow numbers for CVC | |
| const cvcInput = document.getElementById('cvc'); | |
| cvcInput.addEventListener('input', function(e) { | |
| e.target.value = e.target.value.replace(/\D/g, ''); | |
| }); | |
| // Form submission | |
| const paymentForm = document.getElementById('payment-form'); | |
| paymentForm.addEventListener('submit', function(e) { | |
| e.preventDefault(); | |
| // Get form values | |
| const cardNumber = cardNumberInput.value.replace(/\s+/g, ''); | |
| const expiryDate = expiryDateInput.value; | |
| const cvc = cvcInput.value; | |
| const cardholder = document.getElementById('cardholder').value; | |
| // Simple validation | |
| if (!cardNumber || !expiryDate || !cvc || !cardholder) { | |
| alert('Please fill in all fields'); | |
| return; | |
| } | |
| if (cardNumber.length < 16) { | |
| alert('Please enter a valid card number'); | |
| return; | |
| } | |
| if (cvc.length < 3) { | |
| alert('Please enter a valid CVC'); | |
| return; | |
| } | |
| // Show loading state | |
| const submitBtn = paymentForm.querySelector('button[type="submit"]'); | |
| submitBtn.disabled = true; | |
| submitBtn.innerHTML = '<span>Processing...</span>'; | |
| // Prepare payment data | |
| const paymentData = { | |
| cardNumber: cardNumber, | |
| expiryDate: expiryDate, | |
| cvc: cvc, | |
| cardholder: cardholder | |
| }; | |
| // Make API call | |
| fetch('http://localhost:5000/api/payments', { | |
| method: 'POST', | |
| headers: { | |
| 'Content-Type': 'application/json', | |
| }, | |
| body: JSON.stringify(paymentData) | |
| }) | |
| .then(response => response.json()) | |
| .then(data => { | |
| alert('Payment processed successfully!'); | |
| paymentForm.reset(); | |
| }) | |
| .catch(error => { | |
| alert('Error processing payment: ' + error.message); | |
| }) | |
| .finally(() => { | |
| submitBtn.disabled = false; | |
| submitBtn.innerHTML = '<span>Submit Payment</span><i data-feather="arrow-right" class="ml-2"></i>'; | |
| feather.replace(); | |
| }); | |
| }); | |
| }); |