How can I detect when a user has chosen which file to upload using a html file input. That way I can submit the form automatically.
Asked
Active
Viewed 1.7k times
3 Answers
16
The file upload element fires an onchange event when its contents have changed. Here's a very terse example:
<input type="file" name="whatever" onchange="alert('Changed!');" />
EDIT: Oh, and if you'd like to submit the form when they select something (although this will probably be a little confusing to your users):
<input type="file" name="whatever" onchange="this.form.submit();" />

Faisal
- 4,687
- 1
- 19
- 13
-
Just noticed that you're using jQuery, in which case you'll want to use the change() event like Reigel suggested. – Faisal Jul 11 '10 at 22:05
10
A vanilla JavaScript way to detect a change in the file input:
var fileInput = document.getElementById('inputfileID')
fileInput.addEventListener('change', function () {
// Called when files change. You can for example:
// - Access the selected files
var singleFile = fileInput.files[0]
// - Submit the form
var formEl = document.getElementById('formID')
formEl.submit()
}, false);
Just to mention: the attribute false
means to not use capture i.e. false
means that relevant change
listeners in the DOM tree are executed in bottom-up order. It is the default value but you should always give the attribute to maximise compatibility.
See also a SO answer about change event, MDN docs for addEventListener, and a SO answer about form submission.

Akseli Palén
- 27,244
- 10
- 65
- 75