Iterating through formData object in Internet Explorer, using javascript

Viewed 1346

Am creating a formData object using form id and was doing the following:

var formDataDetails = new FormData(document.getElementById("form_id"));
for (var entry of formDataDetails{
     res[entry[0]] = entry[1];
}

Am later doing JSON stringify and doing POST.

But I have found out recently that for..of loop is not supported in 'Internet Explorer' yet. And I believe using for..in loop is not correct since it is used to iterate through enumerable objects (loop through properties of an object rather).

How should I go about iterating through formData, for Internet Explorer?

1 Answers

I am finding that, as of this post, IE still not working reliably in for..of loop through FormData objects. So, my solution, just avoid FormData when you will need to iterate the collection. FormData works fine in IE if you are just using it to post form data.

If you need to iterate the values of the form before they are sent, you could do as I do -- just work directly with the form.elements collection.

Something like this:

export function form2Obj(f) {
   var elemArray = f.elements;
   var formObj = {};
   for (var k in elemArray) {
      var input = elemArray[k];
      if (!input || !input.name || !input.value) continue;
      formObj[input.name] = input.value;  
      // etc, need special handling for inputs of type radio 
      // checkbox, textarea, and select most likely
   }
   return formObj;

}

For the record, I am using webpack to compile to ES6. When I compile in dev mode IE can handle the for..of loop. When I compile in production mode IE does not work.

Related