Alec Smart
Alec Smart

Reputation: 95900

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

Upvotes: 5

Views: 23517

Answers (4)

wal5hy
wal5hy

Reputation: 664

With the version 1.7+ of JQuery:

    //wait for an file input to change anywhere in the document
    $(document).on('change', 'input[type="file"]', function () { 
        $(this).parents('form').submit(); //then submit its parent form
    });

Upvotes: 2

Morg.
Morg.

Reputation: 701

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)

Upvotes: 2

Jon Winstanley
Jon Winstanley

Reputation: 23311

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.

Upvotes: 12

Kirtan
Kirtan

Reputation: 21695

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.

Upvotes: 10

Related Questions