JAVASCRIPT

Collect Form Data and Show Submission Feedback

Discover how to programmatically gather all input values from a form, prevent default submission, and update a specific DOM element to provide real-time user feedback on submission status.

function handleFormSubmission(event) {
  event.preventDefault(); // Prevent default browser form submission

  const form = event.target;
  const formData = {};
  
  // Collect data from all form elements
  Array.from(form.elements).forEach(element => {
    if (element.name && !element.disabled && element.type !== 'submit') {
      if (element.type === 'checkbox' || element.type === 'radio') {
        formData[element.name] = element.checked;
      } else {
        formData[element.name] = element.value;
      }
    }
  });

  console.log('Collected Form Data:', formData);

  const feedbackElement = document.getElementById('formFeedback');
  if (feedbackElement) {
    // Simulate a successful submission and update UI
    feedbackElement.textContent = 'Submission successful! Thank you.';
    feedbackElement.style.color = 'green';
    form.reset(); // Clear the form fields
  } else {
    console.warn('Feedback element with ID "formFeedback" not found.');
  }
}

// Example Usage:
// Assuming HTML: <form id="myForm"><input name="name"/><button type="submit">Submit</button></form><div id="formFeedback"></div>
const myForm = document.getElementById('myForm');
if (myForm) {
  myForm.addEventListener('submit', handleFormSubmission);
}
How it works: This snippet demonstrates how to intercept a form submission, prevent its default behavior (which would cause a page reload), and then programmatically collect all input values. It iterates through the form's elements, extracts their values (handling checkboxes/radios correctly), and stores them in an object. Finally, it updates a designated feedback element in the DOM to inform the user about the submission status, offering immediate client-side feedback.

Need help integrating this into your project?

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

Hire DigitalCodeLabs