Saturday, February 10, 2018

How can I get form data with JavaScript/jQuery?

How can I get form data with JavaScript/jQuery?

JQuery:

let formData = new FormData($('#RegionForm')[0]);

for (let [key, val] of formData.entries()) {
  console.log(key + ': ' + val);
}

JavaScript:

document.querySelector('form').addEventListener('submit', (e) => {
  const formData = new FormData(e.target);

  // Now you can use formData.get('foo'), for example.

  for (let pair of formData.entries()) {
    console.log(pair[0] + ', ' + pair[1]); 
  }

  // Don't forget e.preventDefault() if you want to stop normal form .submission
});

Reference:

https://stackoverflow.com/questions/2276463/how-can-i-get-form-data-with-javascript-jquery

No comments: