jQuery trigger file input

This is due to a security restriction.

I found out that the security restriction is only when the <input type="file"/> is set to display:none; or is visbilty:hidden.

So i tried positioning it outside the viewport by setting position:absolute and top:-100px; and voilà it works.

see http://jsfiddle.net/DSARd/1/

call it a hack.

Hope that works for you.


this worked for me:

JS:

$('#fileinput').trigger('click'); 

HTML:

<div class="hiddenfile">
  <input name="upload" type="file" id="fileinput"/>
</div>

CSS:

.hiddenfile {
 width: 0px;
 height: 0px;
 overflow: hidden;
}

>>>Another one that works Cross-Browser:<<<

The Idea is that you overlay an invisible huge "Browse" button over your custom button. So when the user clicks your custom button, he's actually clicking on the "Browse" button of the native input field.

JS Fiddle: http://jsfiddle.net/5Rh7b/

HTML:

<div id="mybutton">
  <input type="file" id="myfile" name="upload"/>
  Click Me!
</div>

CSS:

div#mybutton {

  /* IMPORTANT STUFF */
  overflow: hidden;
  position: relative;   

  /* SOME STYLING */
  width:  50px;
  height: 28px;
  border: 1px solid green;
  font-weight: bold
  background: red;
}

div#mybutton:hover {
  background: green;
}

input#myfile {
  height: 30px;
  cursor: pointer;
  position: absolute;
  top: 0px;
  right: 0px;
  font-size: 100px;
  z-index: 2;

  opacity: 0.0; /* Standard: FF gt 1.5, Opera, Safari */
  filter: alpha(opacity=0); /* IE lt 8 */
  -ms-filter: "alpha(opacity=0)"; /* IE 8 */
  -khtml-opacity: 0.0; /* Safari 1.x */
  -moz-opacity: 0.0; /* FF lt 1.5, Netscape */
}

JavaScript:

$(document).ready(function() {
    $('#myfile').change(function(evt) {
        alert($(this).val());
    });
});

You can use LABEL element ex.

<div>
    <label for="browse">Click Me</label>
    <input type="file" id="browse" name="browse" style="display: none">//
</div>

This will trigger the input file


I have it working (=tested) in IE8+, recent FF and chrome:

$('#uploadInput').focus().trigger('click');

The key is focusing before firing the click (otherwise chrome ignores it).

Note: you do NEED to have your input displayed and visible (as in, not display:none and not visibility:hidden). I suggest (as many other have before) to absolutely position the input and throw it off screen.

#uploadInput {
    position: absolute;
    left: -9999px;
}

Check out my fiddle.

http://jsfiddle.net/mohany2712/vaw8k/

.uploadFile {
  visibility: hidden;
}

#uploadIcon {
  cursor: pointer;
}
<body>
  <div class="uploadBox">
    <label for="uploadFile" id="uploadIcon">
      <img src="http://upload.wikimedia.org/wikipedia/commons/thumb/3/34/Icon_-_upload_photo_2.svg/512px-Icon_-_upload_photo_2.svg.png"  width="20px" height="20px"/>
    </label>
    <input type="file" value="upload" id="uploadFile" class="uploadFile" />
  </div>
</body>