I am trying to have a single text link on which the user clicks and it asks the user which file he/she wants to upload then, auto matically POSTs it to the form. How can I achieve the same? I know I have to style my file input but how to get it to post automatically on file selection?
Thank you very much
Ordinary input of type file in webpages comes with a default style and the caption, choose file. The good news is that we can style and tweak it to what we want.
In terms of styling, just hide1 the input element using the attribute selector. Then all you need to do is style the custom label element. (example). - It's worth noting that if you hide the element using display: none , it won't work in IE8 and below.
Instant form submission using JavaScript 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.
Embedding javascript in the page is bad practice.
Add the submit to the item using a selector. This also enables you to add the functionality to a basic link, as you have requested.
HTML
<form id="myForm">
<a id="uploadLink" href="#">Upload file</a>
</form>
jQuery
$(document).ready(function() {
$("#uploadLink").click(function() {
$("#myForm").submit();
}
});
Here is a link to the jQuery Form plugin.
There is also a multi-file upload plugin for jQuery.
You can call the submit method of your form. It will submit your page to the server and you can get the file in the Files collection of the request.
You'll have to call the submit() method of the form on the "onchange" event of the "file" element.
<input type="file" onchange="formname.submit();" id="f" />
EDIT: Try this.
Ok , well jQuery may not always be the answer but I'm currently abusing it - mostly for selectors and live stuff - anyway using jQuery, the best solution for your problem is the following:
$('input[type:"file"]').live('change',function(){
$(this).parents('form').submit();
});
This basically makes any input type file auto submit it's parent form - bit overkill you can easily limit this by changing the input type file selector to the class of your choice.
And you can also make it lighter by not using live (I do because I use it dynamically)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With