Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Style input file and auto submit

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

like image 957
Alec Smart Avatar asked Apr 27 '09 10:04

Alec Smart


People also ask

Can I style input type file?

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.

How do I style a file input field?

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.

How do i auto submit an upload form when a file is selected?

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.


3 Answers

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();
    }
});

Additonal resources

Here is a link to the jQuery Form plugin.

There is also a multi-file upload plugin for jQuery.

like image 130
Jon Winstanley Avatar answered Oct 23 '22 22:10

Jon Winstanley


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.

like image 26
Kirtan Avatar answered Oct 23 '22 22:10

Kirtan


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)

like image 21
Morg. Avatar answered Oct 23 '22 22:10

Morg.