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
- Watch: 🎦Using FormData Objects Effectively - Steve Griffith
- Read: 📃FormData - javascript.info
Activity Instructions
- Create a simple form as given in the example from the reading.
- Modify the script by using event listeners for DOMContentLoaded and form submission.
- 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.
- 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));
}
});
});