How to link an input button to a file select window? [duplicate]

Possible Duplicate:
Jquery trigger file input

I’m working on a form which allows users to upload images to a website. So far I have got a drag and drop solution working in Chrome and Safari. However I also need to support the action of users clicking a button and browsing for files in the traditional manner.

Similar to what this would do:

<input type="file" name="my_file">

However rather than having the clunky file description area and un-editable Browse button I would rather use something like this:

<input type="button" id="get_file">

My question therefore is how to I make this button open a file selection window and process the selection the same way that type="file" would work?

Cheers.


My Solution

HTML:

<input type="button" id="my-button" value="Select Files">
<input type="file" name="my_file" id="my-file">

CSS:

#my-file { visibility: hidden; }

jQuery:

$('#my-button').click(function(){
    $('#my-file').click();
});

Working in Chrome, Firefox, and IE7+ so far (haven’t tried IE6).

You could use JavaScript and trigger the hidden file input when the button input has been clicked.

http://jsfiddle.net/gregorypratt/dhyzV/ – simple

http://jsfiddle.net/gregorypratt/dhyzV/1/ – fancier with a little JQuery

Or, you could style a div directly over the file input and set pointer-events in CSS to none to allow the click events to pass through to the file input that is “behind” the fancy div. This only works in certain browsers though; http://caniuse.com/pointer-events

If you want to allow the user to browse for a file, you need to have an input type="file" The closest you could get to your requirement would be to place the input type="file" on the page and hide it. Then, trigger the click event of the input when the button is clicked:

#myFileInput {
    display:none;
}

<input type="file" id="myFileInput" />
<input type="button"
       onclick="document.getElementById('myFileInput').click()" 
       value="Select a File" />

Here’s a working fiddle.

Read More:   Angularjs Bootstrap modal closing call when clicking outside/esc

Note: I would not recommend this approach. The input type="file" is the mechanism that users are accustomed to using for uploading a file.


The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .

Similar Posts