How do I auto-submit an upload form when a file is selected?

You can simply call your form's submit method in the onchange event of your file input.

document.getElementById("file").onchange = function() {
    document.getElementById("form").submit();
};

http://jsfiddle.net/cwvc4/73/


Just tell the file-input to automatically submit the form on any change:

<form action="http://example.com">
    <input type="file" onchange="form.submit()" />
</form>

This solution works like this:

  • onchange makes the input element execute the following script, whenever the value is modified
  • form references the form, that this input element is part of
  • submit() causes the form to send all data to the URL, as specified in action

Advantages of this solution:

  • Works without ids. It makes life easier, if you have several forms in one html page.
  • Native javascript, no jQuery or similar required.
  • The code is inside the html-tags. If you inspect the html, you will see it's behavior right away.

Using jQuery:

$('#file').change(function() {
  $('#target').submit();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="target" action="destination.html">
  <input type="file" id="file" value="Go" />
</form>

JavaScript with onchange event:

<form action="upload.php" method="post" enctype="multipart/form-data">
     <input type="file" name="filename" onchange="javascript:this.form.submit();">
</form>

jQuery .change() and .submit():

$('#fileInput').change(function() {
  $('#myForm').submit();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<form action="upload.php" id="myForm">
     <input type="file" id="fileInput">
</form>

The shortest solution is

<input type="file" name="file" onchange="javascript:document.getElementById('form').submit();" />