Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to trigger click on input file element by clicking on another element

I am using jQuery and Ajax on a button, to update the value of attribute "accept" on an input file upload element, then trigger click on it. But I can only do it on Firefox. On Chrome, the trigger click event doesn't work, and on IE8, it works but cannot upload the selected file. What should I do? This is my code in handleAjaxResponseSuccess function:

$('#inputFile').attr('accept', '.jpg, .png');
$('#inputFile').click();
//in Firefox and IE8, it shows a file dialog that allows choosing file to upload. But in Chrome, the file dialog does not appear, and in IE8, the selected file cannot be uploaded

My HTML code

<button type="button" id="uploadBtn" onclick="getAcceptedExtension()"title="Upload" class=""></button>
<input type="file" name="" id="inputFile" multiple="multiple"style="display: none;" >
like image 395
omglolgg Avatar asked Jan 29 '26 13:01

omglolgg


1 Answers

For the security reasons some browsers don't allow to trigger file input directly. The action to open the dialog box MUST be called by a user interaction (a click for instance) AND the input file MUST be visible (display != none) and focused.

You can show to open dialog and after hide like this:

getAcceptedExtension = function() {
  $('#inputFile').attr('accept', '.jpg, .png');
  $('#inputFile').show();
  $('#inputFile').focus();
  $('#inputFile').click();
  $('#inputFile').hide();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="button" id="uploadBtn" onclick="getAcceptedExtension()"title="Upload" class="">CLICK ME</button>
<input type="file" name="" id="inputFile" multiple="multiple"style="display: none;" >
like image 129
Edson Henrique Avatar answered Jan 31 '26 01:01

Edson Henrique



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!