How do I submit a "file" input without submit button using JavaScript? - 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.

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>

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.

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.

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.

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.

The solutions that were here to add an event listener in the input didn't work for me, so I found another solution, and I wanted to share it.
HTML:
<form id="attachUpload" method="POST" action="javascript:void(0)" accept-charset="utf-8" enctype="multipart/form-data">
<input id="uploadAttachment" type="file" name="files[]" placeholder="Computer" multiple />
</form>
The code to submit the form:
$(document).on('change', '#uploadAttachment', function() {
$('#attachUpload').trigger('submit');
});
And than if you want to post that data after the form is submitted:
$(document).on('submit', '#attachUpload', function(e) {
// code here
})

Related

jQuery submits only one form when multiple forms are submitted

I am writing a chrome extension. In my content script I am injecting two forms into the DOM with target = "_blank". The forms are visible on the page
Form 1
<form action="page1.php" target="_blank" id="form1" method="POST">
<input type="submit" value="Save" id="savebutton1">
</form>
Form 2
<form action="page2.php" target="_blank" id="form2" method="POST">
<input type="submit" value="Save" id="savebutton2">
</form>
I want to submit the two forms using jQuery so I wrote ;
$( "#form1" ).submit();
$( "#form2" ).submit();
But finally only one tab opens, that is only the last form submits and my first form is ignored. But I want to open two tabs
I can not only see page2.php in one tab. My page1.php is never called. Please help in fixing the issue
This is not possible.
The browser can only submit one form and handle whatever redirect that single form generates at server.
If you need multiple forms to submit you would need a different approach such as using ajax
As #charlietfl said, this can't be done as you are trying to do it.
However, depending upon your back end system, you may be able to make a composite form and parse the data there. C#, I know, can handle this.
<input name="form1.xxx">
<input name="form2.xxx">
Then, in C# you could create your object
class Form1 {
xxx: string
}
class Form2 {
xxx: string
}
class Combined {
form1: Form1,
form2: Form2
}
Access it with: Combined.form1.xxx

how to prevent an onchange inside a form from running when clicking submit

I have a form that submits data along with images that are uploaded with an onchange ajax function inside the form. They are added with hidden tags when the upload runs, but the problem is that the last image upload is running again when the form is submitted, probably because of the onchange function being inside the form.
Is there any way to prevent the onchange from running again when somebody clicks the submit button? The structure is like this:
<form id="upload_form" action="new.php" method="post" enctype="multipart/form-data" name="ad_create_form">
<input class="upload_button" type="file" name="item_file_upload_1" id="item_file_upload_1"
onchange="media_sync(ad_create_form, 1,
this.form.item_file_upload_1,
document.getElementById('item_file_url_1').value,
document.getElementById('item_file_embed_1').value,
document.getElementById('nb_uploads_1').value,
5,
'000000015');" />
<input name="finish" id="finish" value="Add" type="submit" class="btn">
</form>
So I'd need the onchange to run as many times as somebody clicks on the upload button, but not anymore when somebody clicks on the submit button. Is that possible?
This is more of a brainstorming idea than a decent answer, but hopefully it will give you ideas that lead to a solution.
Simplistic idea: create a var that tells you if the submit button has been pressed, and look for it in the onchange function.
For example:
var no_run = false;
function media_sync(data){
if (!no_run){
//ajax code goes here - files uploaded
}
}
$('form').submit(function(){
no_run = true;
});
Note that you must define the no_run var outside any functions.
jsFiddle to play with

jquery prevent reload form on submit

I want to upload files using javascript/jquery/ajax and in my case, I have to prevent the reload on form submitting on upload.
Also, I want to add a delete button, such that, when file is uploaded, the delete button can delete this and same is the scenario, that to prevent the page refresh/reload on form submitting.
Hence, I've three buttons in a single form, UPLOAD, DELETE, NEXT and in my case, only next allows to submit the form by refreshing/action of form. And obviously, when file is just selected and the user directly hits the next button, it first uploads and then take his action.
HTML:
<form name="myform" method="post" id="FORM2" enctype="multipart/form-data">
// OTHER VALUES OF FORM
<input type="file" name="FileUpload-1" id="FileUpload-1" class="file_upload" />
<input type="submit" value="Upload" id="upload" class="submitUpload" />
<input type="submit" value="Delete" id="delete" class="submitDelete" />
<input type="submit" name="" id="FORMSUBMIT">
</form>
JS:
$(".submitUpload").click(function(){ console.log('UPLOAD');
action = "upload.php";
$("#FORM").on('submit',function(){
var options={
url : action,
success : onsuccess
};
$(this).ajaxSubmit(options);
return false;
});
}
return false;
});
$(".submitDelete").click(function(){ console.log('DELETE');
return false;
});
$('.FORMSUBMIT').click(function () {
//CUSTOM HANDLING
});
To Directly answer your question:
$("#FORM").on('submit',function(evt){
evt.preventDefault();
});
This piece of code will prevent the normal form submitting.
My advice is to transform the Update and Delete buttons from type=submit to type=button. Like this:
<input type="button" value="Delete" id="Delete" class="submitDelete" />
This will prevent the form to be submitted when delete or update are pressed...
I wrote a jsfiddle for you:
https://jsfiddle.net/yL35bh10/
I recently prototyped a page needing image file upload. I found a package on GitHub that was easy to use and should provide the majority of the functionality you're needing.
https://github.com/blueimp/jQuery-File-Upload
My only question to you: Once a file is uploaded to the server, how are you going to know what to delete?

Submit form to new window only when specific submit button is pressed?

I have a form, which has a few different submit buttons on it all doing different things with the same post data.
Lets say for simplicity sake the form looks like this:
<form method="post">
<input type="hidden" name="ids" value="1,2,3,4" />
<input type="submit" id="picking" name="picking" value="Picking" />
<input type="submit" id="shipping" name="shipping" value="Shipping" />
<input type="submit" id="invoice" name="invoice" value="Invoice" />
</form>
At the moment the form submits to itself and I work out server side which submit button is pressed, build a URL from the POST data, then do a PHP redirect to what I need to go. This works fine.
However, I am looking for the form to post its data to a new window, but only when "invoice" is clicked. This rules out just adding target="_blank" to the form, as the other 2 buttons would submit to new pages as well.
I also can't split the form into 3 different forms as the data is a lot more complex than the above, and a lot of it is input by the user.
Is there a way to do this using JavaScript/JQuery? If so, where would I start?
Thanks
could you not add target blank to the form when invoice is clicked?:
$("#invoice").click(function(){
$('#form_id').attr('target', '_blank');
});
or:
$(document).on("click","#invoice",function(){
$('#form_id').attr('target', '_blank');
});
Try adding a click handler to the correct submit button.
$('#invoice').on('click', function(){
//doStuff
});
This will allow you to control the action of #invoice without affecting the others.

jQuery to submit form on file selection not working

I am trying to initiate upload of a file as soon as the user selects the file. The form should disappear replaced by the "Uploading your picture..." message.
So far, all I get is the form being hidden (and message showing), but the upload is not happening. The form is not being submitted. Any ideas why?
This is the JS
<script>
$(function(){
$("#file_select").change(function(){
$(this).parents("#upload_form").submit();
$("#upload_form_div").hide();
$("#loading").show();
});
});
</script>
and the HTML
<div class="float_left" id="upload_form_div">
<h3>Select a picture for your profile (4 MB max):</h3>
<form action="http://example.com/profile/upload_picture"
id="upload_form"
enctype="multipart/form-data"
method="post" accept-charset="utf-8">
<input type="file" name="userfile"
id="file_select" />
<input type="hidden" name="upload" value="upload" />
<button id="submit" type="submit"><img height="24" width="24"
alt="Upload" src="images/icons/small/white/bended%20arrow%20right.png">
<span>Upload</span>
</button>
</form>
<form action="http://example.com/profile/remove_picture"
method="post" accept-charset="utf-8">
<button type="submit"><img height="24" width="24"
alt="Remove" src="images/icons/small/white/trashcan.png">
<span>Remove</span>
</button>
</form>
</div>
<div id="loading" style="display:none;">
Uploading your picture...
</div>
It probably has something to do with this part:
<input type="file" name="userfile"
value="onchange="return validateFileExtension(this)""
id="file_select" />
An input type=file should not have a value= attribute (and even if it did, you shouldn't put javascript in there!)
You also have some javascript in the form:
onsubmit="return validateFileExtension(this.userfile)"
If the function validateFileExtension() returns false then the form will not submit.
However, the way you have written the jQuery means that the message will still appear.
EDIT:
Change the id on your submit button to something other than "submit".
In the jQuery docs:
Forms and their child elements should not use input names or ids that conflict with properties of a form, such as submit, length, or method. Name conflicts can cause confusing failures. For a complete list of rules and to check your markup for these problems, see DOMLint.
HOWEVER:
You should consider #Abdul's solution, since the working submit will take you away from your message.
If you are using CodeIgniter and you don't want to use Ajax, you should consider using the flash functionality to display the message to the user after the form submits.
You should think of using jquery form plugin to submit your form and jquery validate plugin to validate your form for file extensions and everything.Jquery form plugin submits your form using ajax. In that way you won't be redirected to form action. Also
if you want you can consider using jquery dialog to display the result.
$("#upload_form").validate({
rules: {
MyFile: {
required: false,
accept: "jpg|jpeg|png|gif"
}
}
});
$("#file_select").change(function(){
("#upload_form").ajaxSubmit();
$("#upload_form_div").hide();
$("#loading").show();
});
Submit form on file selection and validate for CSV file input
$('#file').change($('form').submit());
$('form').submit(function(){
if($('#file').val().toLowerCase().indexOf('.csv') != -1){
$('#spinner').show();
return true;
}
else{
alert('Invalid File format. Please, upload CSV file')
return false;
}
});

Categories