JAVASCRIPT
Handle Form Submission and Input Events
Discover how to capture user input from form fields and respond to form submission events using JavaScript, preventing default browser behavior for custom validation.
const myForm = document.getElementById('myForm');
const myInput = document.getElementById('myInput');
// Assuming <form id="myForm"><input type="text" id="myInput"><button type="submit"></button></form>
myForm.addEventListener('submit', function(event) {
event.preventDefault(); // Prevents default form submission (page reload)
console.log('Form submitted!');
console.log('Input value on submit:', myInput.value);
// Perform custom validation or AJAX submission here
});
myInput.addEventListener('input', function() {
console.log('Input changed in real-time:', myInput.value);
});
How it works: This code demonstrates how to handle events on a form and its input field. It attaches an event listener to the form's 'submit' event, preventing the default browser behavior with `event.preventDefault()`. It also logs the input value upon submission and logs changes to the input field in real-time using the 'input' event, useful for validation or interactive feedback.