Pablo
Pablo

Reputation: 4313

Detect when a user chooses a file using a file input

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.

Upvotes: 17

Views: 19378

Answers (3)

Akseli Palén
Akseli Palén

Reputation: 28161

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.

Upvotes: 12

Reigel Gallarde
Reigel Gallarde

Reputation: 65264

try

$('#inputfileID').change(function(){
alert(0);
})​

Upvotes: 9

Faisal
Faisal

Reputation: 4697

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();" />

Upvotes: 16

Related Questions