2

When the user selects files to be uploaded I present one of two buttons to take action on the file(s) based on how many files there are. I get the number of files by including an onchange=getNumFiles(this) in the file input tag.

My problem is that I hide the button to take action on the files after the user clicks it, and if the user selects the same file(s) a second time the button is not "re-presented". This is happening because the file upload input never actually changed because the input is still holding the original file selection. How can I account for this?

Is there a way to clear the contents of the file upload input? I've tried setting the value to null to no avail. Or is there a different event other than onchange that I should be using? hope this makes sense....

A.O.
  • 3,733
  • 6
  • 30
  • 49
  • Possible duplicate of [How can I clear an HTML file input with JavaScript?](https://stackoverflow.com/questions/1703228/how-can-i-clear-an-html-file-input-with-javascript) – Fraser Aug 24 '17 at 09:46

1 Answers1

2

"Is there a way to clear the contents of the file upload input"

Yes, call .reset() on the form.

$("#myform")[0].reset();

Now if the same file is selected again it will correctly trigger a change event since it changed from nothing to something again.

Kevin B
  • 94,570
  • 16
  • 163
  • 180
  • one question, why exactly do you need the array notation [0] to reference forms? – A.O. Sep 11 '13 at 19:19
  • 1
    Because jQuery doesn't have a .reset() method. .reset is a native method that all forms have, it normally gets called when a `` is clicked, it resets all inputs back to their default values. – Kevin B Sep 11 '13 at 19:21
  • the only other way to clear a file input is to clone it or remove it and create a new one. you have little to no access to the value of a file input. – Kevin B Sep 11 '13 at 19:23