After saving the in...">

After resetting the input field, the variable becomes empty

<input type="file" onchange="uploadFiles()" multiple/>

      

After saving 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 == []
}

      

How can I fix this?

+3


source to share


2 answers


$('input')[0].files

gives you a FileList property input

that is bound to it. Changing the input value will change the property value and all of its assignments.

You can fix 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. However, I haven't tested it. If you can confirm or debunk, please comment.

+1


source


This is because your event is onchange

fired a second time when you reset the input field. Resetting an input field is considered a change.

In this case, you can temporarily disable events onchange

when the value is updated.



// remove the change handler
$('input').off('change', uploadFiles);
$('input').val('');
// re-establish the change handler
$('input').on('change', uploadFiles);

      

Note. It is not recommended to mix inline ( onchange="whatever"

) event handlers with handlers in a script. You should just jQuery on()

.

+1


source







All Articles