Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variable becomes empty after resetting input field

Tags:

jquery

input

<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?

like image 935
user7713452 Avatar asked Mar 21 '26 06:03

user7713452


1 Answers

$('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.

like image 144
Alexandru Severin Avatar answered Mar 22 '26 18:03

Alexandru Severin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!