Immediately submit upload form after selecting file

In this post, we are going to see how to submit an HTML form with input type file immediately after one select a file. That means when one selects a file it should submit instantly to upload.

It is always the best way to learn from the example. So here we are going to see an example code snippets that will do this task. Before we go forward, suppose we have an HTML form with a file input type that is given below:

<form action="action_page.php" id="upload_form" method="post" enctype="multipart/form-data">
   <input type="file" id="myfile" name="myfile">
   <input type="submit">

Now we want the above form with to be submitted instantly when we choose a file from the uploader.

We can do it easily using both core JavaScript and also using jQuery.

Instant form submission using JavaScript

Below is the JavaScript code that will submit the form immediately after selecting file:

<script type="text/javascript">
  document.getElementById("upload_form").onchange = function() {
      // submitting the form

In the above code, we have used the onchange method of JavaScript. This method helps to detect the changes of the file input field. After that, we have used the submit() method to submit the form automatically. If you test it on your browser then you will see that the form submitted automatically when you select a file.

Using jQuery to submit uploader form immediately

This task also can be done by using jQuery. Below is the jQuery code that will do that easily:

<script type="text/javascript">
	$('#myfile').change(function() {
	// submit the form 

We have used the jQuery change method to detect the change in uploader input field by the id of the field and then submit the form automatically using JavaScript submit method. If you test it on your browser, then you will see the same thing is happening in here also. it will submit the form instantly after you select a file.

So, you have seen how easy it is to submit a form automatically when you select a file through the uploader. I hope you will be helpful and use this knowledge in your work.

2 responses to “Immediately submit upload form after selecting file”

  1. Joel Lim says:

    I tried both methods but the script does not auto submit after file is selected.

Leave a Reply

Your email address will not be published. Required fields are marked *