<input type="file" onchange="uploadFiles()" multiple/>
After storing the input value in a variable and resetting the input field, the variable becomes empty
function uploadFiles(){
var newFiles = $('input')[0].files;
$('input').replaceWith($('input').val('').clone(true));
console.log(newFiles); // result == []
}
Please how do I fix this?
$('input')[0].files gives you the FileList property of the input, which is attached to it. Changing the value of the input will result in changing the value of the property and all its assignments.
You can work around the problem by adding the files to a separate array:
var newFiles = $('input')[0].files;
var filesArray = [];
for(var i=0; i<newFiles.length; i++){
filesArray[i] = newFiles[i];
}
$('input').replaceWith($('input').val('').clone(true));
console.log(newFiles); // result == []
console.log(filesArray); // result == [File]
Demo
Note: For security reasons, you may or may not use the Files as intended after changing the value of the original input. I haven't tested it though. If you can confirm or debunk, please comment.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With