WDD 330: Web Frontend Development II

FormData Objects

Overview

JavaScript has a built in object named FormData that can help us process HTML form data.

"The FormData object lets you compile a set of key/value pairs to send using XMLHttpRequest. It is primarily intended for use in sending form data, but can be used independently from forms in order to transmit keyed data." - MDN

Prepare

Activity Instructions

  1. Create a simple form as given in the example from the reading.
  2. Modify the script by using event listeners for DOMContentLoaded and form submission.
  3. Modify the script to not use the referenced server code because your external fetch request will be rejected, but instead gather the data and output it to the console upon form submission as demonstrated in the video.
  4. Modify the script by using a FormData append or set method to append the current date as an addition named field in the data set.
Example Solution
document.addEventListener('DOMContentLoaded', () => {
  const formElem = document.getElementById('formElem');
  formElem.addEventListener('submit', (event) => {
    event.preventDefault();
    const formData = new FormData(formElem);
    formData.append('submitted', new Date());
    for (let key of formData.keys()) {
      console.log(key, formData.get(key));
    }
  });
});