JavaScriptRegenerated / yieldmachine

Components for State Machines, using Generator Functions
https://regenerated.dev/yieldmachine
MIT License
33 stars 0 forks source link

Support `formdata` event when FormData is created from form #31

Open RoyalIcing opened 2 years ago

RoyalIcing commented 2 years ago

See: https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement/formdata_event

const formElem = document.querySelector('form');

// submit handler

formElem.addEventListener('submit', (e) => {
  // on form submission, prevent default
  e.preventDefault();

  console.log(form.querySelector('input[name="field1"]')); // FOO
  console.log(form.querySelector('input[name="field2"]')); // BAR

  // construct a FormData object, which fires the formdata event
  const formData = new FormData(formElem);
  // formdata gets modified by the formdata event
  console.log(formData.get('field1')); // foo
  console.log(formData.get('field2')); // bar
});

// formdata handler to retrieve data

formElem.addEventListener('formdata', (e) => {
  console.log('formdata fired');

  // modifies the form data
  const formData = e.formData; 
  // formdata gets modified by the formdata event
  formData.set('field1', formData.get('field1').toLowerCase());
  formData.set('field2', formData.get('field2').toLowerCase());
});