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).
This question is related to
javascript
jquery
html
forms
file-upload
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.
Note: I would not recommend this approach. The input type="file"
is the mechanism that users are accustomed to using for uploading a file.
Source: Stackoverflow.com