harishk
harishk

Reputation: 428

How to make an image upload input to submit form when file is chosen?

I have this image upload html code with a button says'upload', so, these both 'input' and 'submit' button are inside an form. so, when user clicks on input, it asks for a image to select, once selected, user needs to click on upload button to submit the image to the form url.

Now i m trying to submit the image to form url without the involvement of upload button. i.e., when user clicks in input field to select an image, it should submit automatically.

<form id="uploadform" target="upiframe" action="upload.php" method="post" enctype="multipart/form-data">
  <input type="file" name="fileToUpload" class="test" onchange="yourFunction()">
</form>

<iframe id="upiframe" name="upiframe" witdh="0px" height="0px" border="0" style="width:0; height:0; border:none;"></iframe>

<script>
function yourFunction() {
    var form = document.getElementById('uploadform');
    form.submit();
  // }); remove this
}
</script>

Any Suggestion is Appreciated..

Upvotes: 1

Views: 6699

Answers (2)

Ankit vadariya
Ankit vadariya

Reputation: 1263

This will work you need to use pure Javascript method

document.getElementById("uploadform").submit();

function yourFunction(){
  document.getElementById("uploadform").submit();// Form submission
}
<form id="uploadform" target="upiframe" action="upload.php" method="post" enctype="multipart/form-data">
  <input type="file" name="fileToUpload" class="test" onchange="yourFunction()">
</form>

<iframe id="upiframe" name="upiframe" witdh="0px" height="0px" border="0" style="width:0; height:0; border:none;"></iframe>

Upvotes: 1

coopwatts
coopwatts

Reputation: 690

Could you use jQuery to listen for change events on the input:

 $('#file').on('change', function() { $('#form').submit(); });

Upvotes: 0

Related Questions