jQuery trigger file input

Viewed 283847

Am trying to trigger an upload box (browse button) using jQuery.
The method I have tried now is:

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

But it doesn't seem to work. Please help. Thank you.

21 Answers

That's on purpose and by design. It's a security issue.

You can click the input file from your JQuery while keeping it hidden fully.

I am using this:

< input type="file" name="article_input_file" id="article_input_file" accept=".xlsx,.xls" style="display: none" >

$("#article_input_file").click();

this works from within any standard script tag in your HTML page.

I think i understand your problem, because i have a similar. So the tag <label> have the atribute for, you can use this atribute to link your input with type="file". But if you don't want to activate this using this label because some rule of your layout, you can do like this.

$(document).ready(function(){
  var reference = $(document).find("#main");
  reference.find(".js-btn-upload").attr({
     formenctype: 'multipart/form-data'
  });
  
  reference.find(".js-btn-upload").click(function(){
    reference.find("label").trigger("click");
  });
  
});
.hide{
  overflow: hidden;
  visibility: hidden;
  /*Style for hide the elements, don't put the element "out" of the screen*/
}

.btn{
  /*button style*/
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>
<div id="main">
<form enctype"multipart/formdata" id="form-id" class="hide" method="post" action="your-action">
  <label for="input-id" class="hide"></label>
  <input type="file" id="input-id" class="hide"/>
</form>

<button class="btn js-btn-upload">click me</button>
</div>

Of course you will adapt this for your own purpose and layout, but that's the more easily way i know to make it work!!

Related