Jquery delete value from FormData object

didsun picture didsun · Jan 22, 2017 · Viewed 12.5k times · Source

how I can delete value from FormData object with same name? I have HTML form with two input files.

<input id="human" type="file" name="file[]" class="docfiles" />
<input id="animal" type="file" name="file[]" class="docfiles" />

For example I want to delete file 1 - with id "human". Any idea how to do this?

Here my demo jsfiddle.

Answer

james_bond picture james_bond · Jan 22, 2017

Manipulate the array of files and re-add the elements minus the one needed to be removed.

var files = formData.getAll("file[]");
files.splice($("[type='file']").index($("#animal")), 1);
formData.delete("file[]");
$.each(files, function(i, v) {
    formData.append("file[]", v);
});

Demo https://jsfiddle.net/nnte528L/