How do I auto-submit an upload form when a file is selected?
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>
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 thevalue
is modifiedform
references the form, that this input element is part ofsubmit()
causes the form to send all data to the URL, as specified inaction
Advantages of this solution:
- Works without
id
s. 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.
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/