Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

clear/reset formData() using javascript

I use formData below, and pass the results. But data is duplicated if the user does it more than once. So I have to clear/reset the formData before adding any value.

I can do it one-by-one like f.name = '', I have tons of keys. Is there any better way to solve the problem?

$('input').change(function(){
// Create a new formdata but at first have to clear/reset it
var fd = new FormData();
var f = $.canvasResize('dataURLtoBlob', data);
f.name = file.name;
fd.append($('#area input').attr('name'), f);
})
like image 557
Maria Jane Avatar asked Sep 19 '16 14:09

Maria Jane


2 Answers

@gurvinder372's answer won't remove your keys from your FormData, it will just set it to an empty string, which is not the same server side.
E.g, in php, if ( isset($_POST["yourKey"]) ) will still evaluate to true.


The best crossbrowser way is unfortunately to create a new FormData object in your situation.

fd = new FormData();

An other possibility, though it's currently only supported by Chrome>=50 and Firefox>=39, is to use the formData.set() method.
This will replace the value at set key, or append it if no such key is there.

formData.set('yourKey', yourValue);

Now to answer the title of the question, in Chrome>=50 and Firefox>=44, you can use for .. of formData.keys() and delete methods of your FormData Object :

var formData = new FormData();
formData.append('yourKey', yourValue);

for (var key of formData.keys()) {
    // here you can add filtering conditions
    formData.delete(key)
    });

or even with its forEach method (apparently with the same poor browser support)

var formData = new FormData();
formData.append('yourKey', yourValue);

formData.forEach(function(val, key, fD){
    // here you can add filtering conditions
    formData.delete(key)
    });
like image 132
Kaiido Avatar answered Sep 21 '22 01:09

Kaiido


Or you can clear the FormData by doing

function clearFormData( fd )
{
  for( var prop in fd )
  {
    if ( typeof fd[ prop ] != "function" )
    {
      fd[ prop ] = "";
    }
  }
}

Another approach using enteries and delete method

var entries = formData.entries();
for(var pair of entries ) 
{
   formData.delete( pair[0] );
}
like image 21
gurvinder372 Avatar answered Sep 22 '22 01:09

gurvinder372