Adam Halasz
Adam Halasz

Reputation: 58301

How to track if file was selected with javascript?

So If I have an input field:

<input type="file" name="file" id="file" />

I click it and select a file and when I press Open I would like to submit the form and upload the file without clicking the button added by <input>.

Upvotes: 0

Views: 151

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1073968

As goreSplatter points out below, be careful that this behavior isn't a surprise in terms of the user experience. For instance, it may be perfectly valid to do this with something that attaches files to an email like GMail does; but unless the user has an opportunity to cancel those attachments, etc., before things are finalized, you might be falling down a UX pothole. But I expect you've probably already worked out the UX aspect and are not doing something silly. :-)

Answering the question: You can do this by using a change event handler, e.g., onchange= or the DOM2 equivalent via addEventListener (or attachEvent on IE).

Example (live copy):

hookEvent(document.getElementById('fileInput'),
          'change',
          inputChanged);

function inputChanged() {
  display("The input's value changed");
}

...where hookEvent is your utility function for hooking up an event handler (see the link below for one example, but it's not optimized; if you use a library like jQuery, Prototype, YUI, Closure, or any of several others, they'll include a means of hooking events cross-browser).

The example linked above works on Chrome, Firefox, and Opera for Linux, IE6 and IE7 on Windows, and so is fairly likely to be well-supported overall.

Upvotes: 2

Related Questions