34

There is a way to automatically submit a form without clicking to a "submit" button?

I have a form with one "file" input. I would submit the form after the user have selected one file.

Prashanth kumar
  • 815
  • 2
  • 8
  • 26
Pennywise83
  • 1,706
  • 5
  • 27
  • 42

5 Answers5

71

yes, you can use the form.submit() function. Add an onchange listener on the file input and link it to the form.submit() function, like so:

<form action="upload.php" method="post" enctype="multipart/form-data">
<input type="file" onchange="this.form.submit()" name="myFile"/>
</form>
k.vincent
  • 2,975
  • 6
  • 27
  • 56
Marius
  • 54,363
  • 28
  • 121
  • 143
8

Yes, you can add the following to the onchange event of the file input:

<input type='file' .... onchange='this.form.submit();'>

this submits the form right after the user has picked a file. However, the user can't correct a mistaken selection before submitting - be sure to check whether this is really wise.

Pekka
  • 418,526
  • 129
  • 929
  • 1,058
3

This solution works for me.

<form enctype="multipart/form-data" method="POST" action="/upload">
  <input id="myfilefield" type="file" name="file">
  <input type="submit">
</form>

 

document.getElementById('myfilefield').onchange = function() {
  this.form.submit();
};

By the way, you don't need to use flash. Gmail do it by XHR Level 2.

laalto
  • 137,703
  • 64
  • 254
  • 280
cwtuan
  • 1,361
  • 1
  • 13
  • 15
1

I don't believe you can do this. Browsers are very, very strict about what you can do to file upload fields, because of the potential for abuse. If the user accidentally selects a private file, they wouldn't want it to immediately start uploading that file to a random server.

ceejayoz
  • 165,698
  • 38
  • 268
  • 341
  • not true, I just tested the code in my answer, and it works (at least in Firefox). – Marius Dec 14 '09 at 23:17
  • Checked with IE, Edge, Chrome, Firefox - none will accept this, while `onchange='alert("test");'` is fine. Believe, this does not work for enctype multipart/form-data - which is required to have a file-upload work. – dognose Nov 30 '16 at 20:58
  • 1
    edit: http://stackoverflow.com/questions/833032/submit-is-not-a-function-error-in-javascript That's the point. don't name the submit button `submit`, else it fails with console error `submit is not a function`. name it different, then it works. – dognose Nov 30 '16 at 21:02
0

I'm not sure what the restrictions are with doing this in an HTML form.

You can, however, do it with Flash. Gmail does it - when I click "Attach a file", I get prompted with a file browse dialog, and when I OK that dialog the upload begins immediately, and also gives me a progress bar.

Googling for "Flash uploader" will give you many options, but I don't have experience with any of them.

RichieHindle
  • 244,085
  • 44
  • 340
  • 385