Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery delete value from FormData object

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.

like image 845
didsun Avatar asked Jan 22 '17 00:01

didsun


People also ask

How do I delete data from FormData?

delete() The delete() method of the FormData interface deletes a key and its value(s) from a FormData object. Note: This method is available in Web Workers.


2 Answers

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/

like image 164
james_bond Avatar answered Sep 20 '22 19:09

james_bond


You can delete the entire file list by setting the value property of the input object to an empty string.

document.getElementById('human').value = "";

If you are using FormData, you can also have

ForEach(var key in formData.keys()){
  formData.delete(key);
}

This will iterate through all keys in formData and delete all the key value pairs.

like image 22
Riya Avatar answered Sep 22 '22 19:09

Riya