14

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.

Pablo
  • 4,173
  • 7
  • 30
  • 34

3 Answers3

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,553
  • 1
  • 18
  • 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
9

try

$('#inputfileID').change(function(){
alert(0);
})​
Reigel
  • 62,834
  • 21
  • 119
  • 135
9

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
  • 25,849
  • 9
  • 61
  • 72