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

0

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

1

This is because your onchange event gets fired a second time when you reset the input field. Resetting the input field is considered a change.

A way around this would be to temporarily disable the onchange events while you update the value.

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

Note: it isn't a good idea to mix inline event handlers (onchange="whatever") with handlers in your script. You should just jQuery on().

6 Comments

Well spotted. I was about to close as duplicate:stackoverflow.com/questions/415483/…
He is resetting the value by calling .val(''), which doesn't trigger onchange automatically.
@AlexandruSeverin calling .val() isn't the issue, it's replacing the input that's considered the change.
So what's the best way to do that?
@Soviut, replacing an element doesn't trigger onchange either. Demo: jsfiddle.net/zohalexix/4covyham
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.