Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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).

like image 270
diggersworld Avatar asked May 29 '12 12:05

diggersworld


People also ask

Is it possible to make a button as file upload button?

To make a button a file upload button with JavaScript, we can create a hidden file input. And then we add a button that opens the hidden file input when we click it. to add the hidden file input and a button.


1 Answers

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

like image 135
Greg Avatar answered Sep 21 '22 02:09

Greg