Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I submit a "file" input without submit button using JavaScript?

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.

like image 488
Pennywise83 Avatar asked Dec 14 '09 23:12

Pennywise83


People also ask

How can we submit a form without submit button?

The form can be submitted without using submit button by implementing a specific event attribute or by clicking the link. This task can be done by using the OnClick event attribute or by using the form. submit() method in Javascript.

How can I submit a form without using JavaScript?

Use the <noscript></noscript> tags to define a "normal" submit-button when javascript is disabled. Show activity on this post. You could maybe use the <noscript> tag and encapsulate the above code with the button type as submit. If the client has js, the code inside the noscript will be ignored.

How can I upload a file without form?

ajax({ url: 'upload. php', type: 'POST', processData: false, // important contentType: false, // important dataType : 'json', data: myFormData }); You don't have to use a form to make an ajax request, as long as you know your request setting (like url, method and parameters data).


4 Answers

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>
like image 199
Marius Avatar answered Oct 09 '22 01:10

Marius


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.

like image 22
Pekka Avatar answered Oct 09 '22 03:10

Pekka


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.

like image 44
cwtuan Avatar answered Oct 09 '22 02:10

cwtuan


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.

like image 34
ceejayoz Avatar answered Oct 09 '22 01:10

ceejayoz