JAVASCRIPT

Prevent Default Form Submission and Display Dynamic Feedback

Intercept form submissions using `event.preventDefault()`, process input values, and then update the DOM to show a success or error message without a page reload.

const myForm = document.getElementById('myForm');
const feedbackMessage = document.getElementById('feedbackMessage');

if (myForm && feedbackMessage) {
    myForm.addEventListener('submit', function(event) {
        event.preventDefault(); // Stop the browser from refreshing the page
        
        const nameInput = myForm.querySelector('#name');
        const emailInput = myForm.querySelector('#email');

        const name = nameInput ? nameInput.value : '';
        const email = emailInput ? emailInput.value : '';

        // Simulate an asynchronous operation (e.g., sending data to a server)
        setTimeout(() => {
            if (name && email) {
                feedbackMessage.textContent = `Thank you, ${name}! Your email (${email}) has been received.`;
                feedbackMessage.style.color = 'green';
                myForm.reset(); // Clear form fields
            } else {
                feedbackMessage.textContent = 'Please fill in all fields.';
                feedbackMessage.style.color = 'red';
            }
        }, 1000);
    });
}

// HTML Structure (example):
// <form id="myForm">
//   <input type="text" id="name" placeholder="Name">
//   <input type="email" id="email" placeholder="Email">
//   <button type="submit">Submit</button>
// </form>
// <p id="feedbackMessage"></p>
How it works: This snippet demonstrates how to prevent the default browser behavior for form submissions using `event.preventDefault()`. Instead of a page reload, it captures form input values, simulates a backend process, and then dynamically updates a feedback message element in the DOM based on the outcome. It also shows how to clear form fields using `myForm.reset()` and modify the feedback message's style, providing a seamless user experience.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs