2

This is my code:

html:

<form>
    <input id = "file" type="file" />

    <div id="custom_button">custom button</div>
</form>

Jquery:

$("#custom_button").on("click", function () {
    $("#file").click();    
});

css:

#file {
    display: none;
}

But this works only in firefox and chrome, in safari and opera, at click on custom button, window for file choosing is not calling

DEMO: http://jsfiddle.net/J4GdN/

Qusetion: why this not works in safari and opera? what is alternative, for making this in these browsers?

Oto Shavadze
  • 40,603
  • 55
  • 152
  • 236
  • It works for me on Safari. – Ram May 01 '13 at 11:39
  • 2
    http://stackoverflow.com/questions/210643/in-javascript-can-i-make-a-click-event-fire-programmatically-for-a-file-input – dt192 May 01 '13 at 11:44
  • 2
    http://stackoverflow.com/questions/12035400/how-can-i-remove-the-no-file-chosen-tooltip-from-a-file-input-in-chrome – Ram May 01 '13 at 11:45

2 Answers2

1

Some user agents disallow triggering click on input-file elements by js especially in css display:none. An alternative is this way:

HTML

<input id="file-element" type="file" name="my-file-upload" />
<div id="file-element-replacement">
    <input type="text" value="" />
    <img alt="custom upload" src="custom-upload.png" />
</div>

CSS

#file-element {
    /* if opacity is 0 => some UAs interpret it like display:none */
    filter: alpha(opacity=1);
    filter: progid:DXImageTransform.Microsoft.Alpha(opacity=1);
    -moz-opacity: 0.01;
    -webkit-opacity: 0.01;
    opacity: 0.01;
    position: relative;
    z-index: 2;
}

#file-element-replacement {
    position: relative;
    top: -20px;
    z-index: 1;
}

Make your input-file tranparent and simulate this with an input-text + image as a layer behind.

Mamuz
  • 1,730
  • 12
  • 14
0

Another option is to use the standard <label> tag, setting the for attribute to the id of the <input>.

You can then hide the <input> and style the <label> as needed.

In my testing this works very well across browsers as it's standard functionality.

adnrw
  • 1,038
  • 6
  • 13
  • Well, Mamuz had a better idea. – cox May 11 '13 at 17:19