17

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.

3 Answers 3

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();" />
Sign up to request clarification or add additional context in comments.

1 Comment

Just noticed that you're using jQuery, in which case you'll want to use the change() event like Reigel suggested.
12

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.

Comments

9

try

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.