1. What is the correct way to prevent form submission?
Event.preventDefault stops the default action of an event. For forms, it prevents page reload on submission. Call preventDefault in the submit event handler. This allows you to validate data and submit via AJAX instead. Return false works in inline HTML but is not recommended. It also stops propagation, which may not be intended. Preventing default is essential for modern web applications that handle forms with JavaScript. You can also prevent default on links, context menus, and other events. Understanding preventDefault is crucial for controlling browser behavior.
const form = document.getElementById('myForm');
// PREVENT FORM SUBMISSION
form.addEventListener('submit', (event) => {
event.preventDefault(); // Stop page reload
console.log('Form submitted');
// Get form data
const formData = new FormData(form);
const data = Object.fromEntries(formData);
console.log(data);
// Validate and send via AJAX
if (validateForm(data)) {
submitForm(data);
}
});
// FORM VALIDATION
function validateForm(data) {
const errors = [];
if (!data.username || data.username.trim().length < 3) {
errors.push('Username must be at least 3 characters');
}
if (!data.email || !data.email.includes('@')) {
errors.push('Invalid email');
}
if (!data.password || data.password.length < 8) {
errors.push('Password must be at least 8 characters');
}
if (errors.length > 0) {
displayErrors(errors);
return false;
}
return true;
}
// ACCESSING FORM DATA
// Method 1: FormData API
const formData = new FormData(form);
console.log(formData.get('username'));
console.log(formData.get('email'));
// Convert to object
const dataObj = Object.fromEntries(formData);
console.log(dataObj); // {username: '...', email: '...'}
// Method 2: Direct access
const username = form.elements.username.value;
const email = form.elements.email.value;
// Method 3: querySelector
const username2 = form.querySelector('input[name="username"]').value;
// REAL-TIME VALIDATION
const emailInput = document.getElementById('email');
const emailError = document.getElementById('emailError');
emailInput.addEventListener('blur', () => {
if (!emailInput.value.includes('@')) {
emailError.textContent = 'Invalid email';
emailInput.classList.add('error');
} else {
emailError.textContent = '';
emailInput.classList.remove('error');
}
});
// Clear error on input
emailInput.addEventListener('input', () => {
emailError.textContent = '';
emailInput.classList.remove('error');
});
// PASSWORD STRENGTH INDICATOR
const passwordInput = document.getElementById('password');
const strengthMeter = document.getElementById('strength');
passwordInput.addEventListener('input', () => {
const password = passwordInput.value;
let strength = 'Weak';
if (password.length >= 8) {
strength = 'Medium';
}
if (password.length >= 12 && /[A-Z]/.test(password) && /[0-9]/.test(password)) {
strength = 'Strong';
}
strengthMeter.textContent = strength;
strengthMeter.className = strength.toLowerCase();
});
// SUBMIT VIA AJAX
async function submitForm(data) {
try {
const response = await fetch('/api/submit', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
});
if (response.ok) {
showSuccess('Form submitted successfully!');
form.reset();
} else {
showError('Submission failed');
}
} catch (error) {
showError('Network error');
}
}
// RESET FORM
const resetBtn = document.getElementById('resetBtn');
resetBtn.addEventListener('click', () => {
form.reset(); // Clear all fields
clearErrors();
});
// PREVENT MULTIPLE SUBMISSIONS
let isSubmitting = false;
form.addEventListener('submit', async (event) => {
event.preventDefault();
if (isSubmitting) return; // Prevent double submit
isSubmitting = true;
const submitBtn = form.querySelector('button[type="submit"]');
submitBtn.disabled = true;
submitBtn.textContent = 'Submitting...';
await submitForm(new FormData(form));
isSubmitting = false;
submitBtn.disabled = false;
submitBtn.textContent = 'Submit';
});
// FILE INPUT HANDLING
const fileInput = document.getElementById('fileInput');
fileInput.addEventListener('change', (event) => {
const files = event.target.files;
if (files.length > 0) {
const file = files[0];
console.log('File:', file.name);
console.log('Size:', file.size);
console.log('Type:', file.type);
// Validate file
if (file.size > 5 * 1024 * 1024) {
alert('File too large (max 5MB)');
fileInput.value = '';
}
}
});